本章將進(jìn)入Vue3.x的魅力所在 setup composition-api的標(biāo)志珍特。
1幔翰、概述:一個(gè)新的Vue的組件選項(xiàng)董习,它是組件中使用composition API的一種標(biāo)志(入口)
2丑念、執(zhí)行:在組件解析完props后,組件創(chuàng)建之前執(zhí)行浪规。也被認(rèn)作為composition API的入口
3或听、參數(shù):props(為組件的props),context(包含attrs笋婿;emit誉裆;slots三個(gè)組件的property)
4、用例:
// user.vue
<script>
export default {
setup(props, context){
...
return {...};
}
}
</script>
5缸濒、調(diào)用時(shí)組件狀態(tài):實(shí)例化還未開始
6足丢、props:需要在組件選項(xiàng)中定義props,并接收傳遞的值庇配,才能在setup中使用其值
// user.vue
<script>
export default {
props: {name: String}
setup(props, context){
console.log(props.name) // 能獲取到
console.log(props.age) // 不能獲取到--undefined
return {...};
}
}
</script>
注意:props為響應(yīng)式代理斩跌,如果使用es6的數(shù)據(jù)解構(gòu)操作,將使得解構(gòu)后的數(shù)據(jù)失去響應(yīng)式(即:不能實(shí)時(shí)獲取到父組件傳來的值)
7捞慌、擴(kuò)展:父組件通過屬性傳的值在子組件中的各個(gè)部分的獲纫弧:
?①:props:通過父?jìng)髯拥姆绞街苯荧@取到值
?②:setup(props, context){} 方法中的props只能拿到選項(xiàng)props中已經(jīng)定義的屬性;
?③:setup(props, { attrs, emit, slots}){} 方法中的attrs只能拿到未在選項(xiàng)props中定義的屬性啸澡;
?④:通過{ proxy } = getCurrentInstance(); proxy.attrs也只能拿到未在選項(xiàng)props中定義的屬性袖订;
8萝快、context:非響應(yīng)式的對(duì)象;包含了組件暴露的三個(gè)property:
?context.attrs:傳入組件中但是未被props接收的對(duì)象著角。
?context.emit:用于觸發(fā)當(dāng)前組件實(shí)例上的傳值事件揪漩。
?context.slots:用來訪問被插槽分發(fā)的內(nèi)容(一般用于使用渲染函數(shù)來書寫一個(gè)組件時(shí))
9、return():若需要在當(dāng)前組件視圖中或其他組件中使用當(dāng)前組件創(chuàng)建的響應(yīng)式變量及方法吏口,則需要導(dǎo)出相應(yīng)的響應(yīng)式變量及方法奄容。
// user.vue
<template>
<p>{{name}}</p>
</template>
<script>
import { ref } from 'vue';
export default {
setup(props, context){
const name = ref('zhang_san');
return { name };
}
}
</script>
return也具有渲染功能:
// user.vue
<script>
import { ref, h } from 'vue';
export default {
setup(props, context){
return() => h('div', { class: 'red' }, '內(nèi)容');
// <template><div class="red">內(nèi)容</div></template>
}
}
</script>
下一章:(五)響應(yīng)式數(shù)據(jù)對(duì)象 - reactive
上一章:(三)Vue3.x應(yīng)用配置
ps:你有沒有發(fā)現(xiàn),某一首歌會(huì)特定成為你放不下的某一個(gè)人产徊,當(dāng)然也或許是某些歌昂勒,某些人。