<!-- 这是一个vue3 -->
<template><div class="person"><h2>姓名:{{name}}</h2><h2>年龄:{{age}}</h2><button @click="changeName">修改名字</button><button @click="changeAge">年龄+1</button><button @click="showTel">点我查看联系方式</button></div></template><script lang="ts">import {ref} from 'vue'export default {name:"Person",beforeCreate() {console.log("beforeCreate");},setup(){console.log(this);console.log("setup"); // 变量定义,使用ref 关键字来定义响应式数据let name = ref('张珊');let age= ref(18);// 函数定义function changeName(){name.value='李思'}function changeAge(){age.value+=1;}function showTel(){alert("15823645923");}// 通过return 返回所有可以在template中可以处理的数据return { name,age,changeName,changeAge,showTel}}}</script><style scoped>.person {background-color: skyblue;box-shadow: 0 0 10px;border-radius: 10px;padding: 20px;}
</style>
- vue3组合式api的入口 .这是vue3中新的配置项 ,可以在setup这个配置项中配置所有想要的东西,如变量 函数 监视器
- setup这个配置项会优于beforeCreate这个钩子函数,而beforeCreate钩子函数是用来初始化vue实例的,因此setup不会指向vue实例,因此setup中就没有this关键字
- setup的返回值通常是一个对象,会将所有需要暴露的数据通过自定义的形式返回出去
上述代码可以使用setup语法糖的方式重构,这样做的好处,是可以避免页面中处理的数据过多,需要一个个定义返回值得情形.这两种方式是等价的,一般建议使用setup 语法糖 setup 语法糖(script setup)的方式
<!-- setup 语法糖,可以避免数据多时,需要手动的return. 等价于上面一种写法 -->
<script lang="ts" setup >import {ref} from 'vue'let name = ref('张珊');let age= ref(18);// 函数定义function changeName(){name.value='李思'}function changeAge(){age.value+=1;
}
function showTel(){alert("15823645923");
}
</script>