setup的基础使用
- setup 是个函数
- 是一个新的组件选项,所有的组合API函数都在此使用,作为在组件内使用 Composition API 的入口点,只在初始化时执行一次
- setup 内部不存在this
- setup 内部如果return出去一个对象,对象的数据或者方法,都能够在模板中直接使用
- setup 相当于beforeCreat 和 created 这两个生命周期函数的合并
<template>
<div class="about">
<h1>This is an about page</h1>
<p>count:{{count}}</p>
<button @click="showCount">按钮</button>
</div>
</template>
<script lang="ts">
import {defineComponent} from "vue";
export default defineComponent({
name:"AboutView",
setup(){
//此定义变量方式没有响应式,vue3提供特殊的具备响应式的定义变量方法
let count = 0;
//内部虽然没有this,但是不影响箭头函数使用,箭头函数内本身也没有this
//函数内部一定要写内容,不然报语法错误
const showCount = () => {
alert(1);
};
return {count,showCount}
},
})
</script>
vue3生命周期图谱:
支持选项式API 和 组合式API
当renderer遇到组件时,使用选项式API就使用beforeCreat 和 created,使用组合式API就使用setup函数
setup的高级使用
- 语法糖setup函数
- 直接写在script标签上,内部不需要return
<template>
<div class="about">
<h1>This is an about page</h1>
<p>count:{{count}}</p>
<button @click="showCount">按钮</button>
</div>
</template>
<script lang="ts">
import {defineComponent} from "vue";
export default defineComponent({
name:"AboutView",
})
</script>
<script lang="ts" setup>
let count = 0;
const showCount = () => {
alert(1);
};
</script>