本章將進(jìn)入Vue3.x的魅力所在 setup composition-api的標(biāo)志。
1、概述:一個新的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三個組件的property)
4、用例:
// user.vue
<script>
export default {
setup(props, context){
...
return {...};
}
}
</script>
5、調(diào)用時組件狀態(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í)時獲取到父組件傳來的值)
7、擴(kuò)展:父組件通過屬性傳的值在子組件中的各個部分的獲取:
?①:props:通過父傳子的方式直接獲取到值
?②: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)式的對象;包含了組件暴露的三個property:
?context.attrs:傳入組件中但是未被props接收的對象。
?context.emit:用于觸發(fā)當(dāng)前組件實(shí)例上的傳值事件。
?context.slots:用來訪問被插槽分發(fā)的內(nèi)容(一般用于使用渲染函數(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ù)對象 - reactive
上一章:(三)Vue3.x應(yīng)用配置
ps:你有沒有發(fā)現(xiàn),某一首歌會特定成為你放不下的某一個人,當(dāng)然也或許是某些歌,某些人。