setup
前面 HelloWorld 中已经使用了 setup, 它是 Vue3 中新的配置项,它的值是一个函数,在 Vue3 中,组件的数据、方法、计算属性、监视器等等,都配置在 setup 中。
setup 主要有以下特点,前面也介绍了几个:
- setup 函数返回的对象,可以直接在
<template>模板中使用; - setup 函数会在
beforeCreate之前执行,也就是在所有的生命周期回调函数之前执行; - setup 函数中是没有 this 的,这个和 Vue2 中的有区别;
下面来实现一个功能,点击页面的按钮,计数+1。
代码如下:
<template>
<!-- 结构 -->
<div class="my-app">
<div>{{ count }}</div>
<button @click="increment">增加</button>
</div>
</template>
<script lang="ts">
import { ref } from 'vue'
// 脚本
export default {
name: "App",
setup() {
// 响应式状态
const count = ref(0)
// 用来修改状态、触发更新的函数
function increment() {
count.value++
}
return {count, increment}
}
}
</script>