内容:
setup是Vue3中新增的巨剑配置项,作为组合API的入口函数。
执行时机:实例创建前调用,升值遭遇Vue2中的 beforeCreate 。
注意点:由于执行setup的时候是咧还没有created,所以在setup中是不能直接使用的data和methods中的数据的,所以Vue3干脆把setup中的this绑定了undefined,防止乱用!
虽然Vue2中的data和methods配置虽然在Vue3中也能使用,但不建议了,建议数据和方法都卸载setup函数中,并通过return惊醒返回可在模板中直接使用(一般情况下setup不能为异步函数)。
<template>
<h1 @click="say()">{
{ msg }}</h1>
</template>
<script>
export default {
setup() {
const msg = 'Hello Vue3'
const say = () => {
console.log(msg)
}
return { msg, say }
}
}
</script>
setup 也可以返回一个渲染函数(问:setup 中 return 的一定只能是一个对象吗?)
<script>
import { h } from 'vue'
export default {
name: 'App',
setup() {
return () => h('h2', 'Hello Vue3')
}
}
new Vue({render: h => h(App)})
</script>