在 Vue3 中的称为组合式 API (Composition API),后面我们将以这种方式来学习,其实在 Vue3 中也是可以以选项式 API 来编程的,也就是 Vue3 是兼容 Vue2 的语法。
在 HelloWorld 中使用了 setup 选项,setup 选项的执行时机是很早的,比组件生命周期函数 beforeCreate 还要早(生命周期后面再讲),所以在 Vue2 的选项式 API 中是可以获取到 setup 返回的信息的,但是 setup 中无法获取 Vue2 选项中的数据。
<template>
<!-- 结构 -->
<div class="my-app">
<button @click="printMsg">打印msg</button>
</div>
</template>
<script lang="ts">
// 脚本
export default {
name: "App",
methods: {
printMsg() {
console.log(this.msg); // 通过this.name获取
}
},
setup() {
let msg = "Hello world";
return {
"msg": msg,
}
}
}
</script>