这里点击改名按钮,会触发methods里定义的changeName函数,会立刻改变页面中name的值
<template> <div class="person"> <h1>姓名:{{ name }}</h1> <h1>年龄:{{ age }}</h1> <!--点击事件用@click --> <button @click="changeName">改名</button> <button @click="showTel">查看联系方式</button> </div> </template> <script lang="ts"> //导出组件名称,叫做"App" export default { //名称 name: "Person", //组件数据仓库 data() { return { name: "张三", age: 18, tel: "138888888" } }, methods: { showTel() { alert(this.tel) }, changeName() { this.name = "zhangsan"//这里是响应式的 } } } </script> <style> .person { background-color: aqua; } </style>VUE3中推荐组合式使用setup函数
setup函数中this是undefined,变量值不是响应式的
<template> <div class="person"> <h1>姓名:{{ name }}</h1> <h1>年龄:{{ age }}</h1> <!--点击事件用@click --> <button @click="changeName">改名</button> <button @click="showTel">查看联系方式</button> </div> </template> <script lang="ts"> export default { //名称 name: "Person", setup(props, ctx) { let name = "张三" let age = 18 let tel = "1388888888" console.log(this)//setup函数中this是undefined function changeName() { console.log("changename start" + name) //这里数据已经改了,但是不是响应式的 name = "zhangsan" console.log("changename after" + name) } function showTel() { alert(tel) } //将属性与方法交出去,让模板能用 return {name, age, changeName, showTel} }, } </script> <style> .person { background-color: aqua; } </style>另外一个,setup也可以直接返回一个lamda函数,替换<template>里的值,用的不多
如果有VUE2的 data 与 methods , setup不能读取data与methods的里值或方法,但是data与mothods能通过this读取到setup里定义的值,因为setup最先加载