在沒有使用setup前的寫法中,在methods的方法或者mounted的方法中我們可以用this來獲取data數據調用一些方法之類的,this指向當前這個組件。
但是在setup中this是undefined的,因為setup方法的調用時機是在boforeCreated方法之前,也就是說在組件還沒有創建之前就調用了setup方法,所以在setup中肯定不存在一個指向當前組件的this。
沒有this那么怎么使用父組件傳入的屬性或者調用父組件的方法,就需要用到setup方法的參數:
如vue3默認生成的HelloWorld組件用setup獲取Home父組件的屬性:
<template>
<div class="hello">
<h1>{{ msg }}</h1>
</div>
</template>
<script>
import { reactive, computed } from "vue";
export default {
name:'Hello',
props:{
msg:{
type:String
}
},
//第一個參數props中可以獲取父組件傳入的參數,
//第二個參數中有很多內容,context.attrs可以獲取父組件的屬性(沒有被子組件接收的那部分,即props中沒有聲明的部分)
//context.slots可以獲取組件中slot部分的內容
//context.parent可以獲取父組件對象
//context.root可以獲取根組件對象
//context.emit用於調用父組件的方法
//context.refs獲取組件上面的元素對象
setup(props,context){
//獲取父組件傳入的屬性
console.log(props.msg);
console.log(this);
const data = reactive({
});
return{data};
}
}