setup 是一個新的元件選項,作為元件中使用組合API的起點。
将來組合Api的代碼,基本都在這個裡面
從元件生命周期來看,它的執行在元件執行個體建立之前vue2.x的beforeCreate執行。
這就意味着在setup函數中 this 還不是元件執行個體,this 此時是 undefined
在模版中需要使用的資料和函數,需要在 setup 傳回。
<template>
<div class="container">
根元件
<div>{{msg}}</div>
<button @click="say()">點選</button>
</div>
</template>
<script>
export default {
name: 'App',
// 1、setup函數是組合Api的起點,将來組合Api的代碼,基本都在這個裡面
// 2、可以了解為:在beforeCreate鈎子函數至向前執行,元件建立執行個體之前
// 3、是以啊含糊中不能使用this,這個時候this ===>undefined
// 4、在模版中需要使用的資料和函數,需要在 setup 傳回。
setup() {
console.log(this) // undefined
// 資料 msg此時可并不是響應式資料
const msg = "hi vue3"
// 方法
const say = () => {
console.log("hello,vite")
}
return {msg,say}
},
beforeCreate() {
console.log(this) // 可以列印出來的
},
};
</script>
<style lang='less' scoped>
</style>