setup 概述
setup
是Vue3
中一个新的配置项,值是一个函数,它是 Composition API
组件中所用到的:数据、方法、计算属性、监视......等等,均配置在setup
中。
特点如下:
setup
函数返回的对象中的内容,可直接在模板中使用。setup
中访问this
是undefined
。setup
函数会在beforeCreate
之前调用,它是“领先”所有钩子执行的
使用
<script setup lang="ts" name="Student">
其中name为组件名称。
代码
Student.vue
<template>
<div>
<h2>{
{ name }}</h2>
<h2>{
{ age }}</h2>
<button @click="updateName">修改名字</button>
<button @click="updateAge">修改年龄</button>
<button @click="showPhone">显示联系方式</button>
</div>
</template>
<script setup lang="ts" name="Student">
import { ref, Ref } from 'vue';
let name=ref('weihu')
let age=ref(18)
function updateName(){
name.value="李四"
}
function updateAge(){
age.value+=1
}
function showPhone(){
alert("18880709")
}
</script>
<style scoped>
</style>
App.vue
<template>
<Student/>
</template>
<script lang="ts">
import Student from './components/Student.vue'
export default {
name:'App', //组件名
components:{Student} //注册组件
}
</script>