1. Setup
Demo 1: Data, function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| <template> <h1>一个人的信息</h1> <h2>姓名: {{ name }}</h2> <h2>年龄: {{ age }}</h2> <button @click="sayHello">说话</button> </template>
<script> export default { name: "App", setup() { let name = "张三"; let age = 18;
function sayHello() { alert(`我叫${name},我${age}岁了,你好啊!`); } return { name, age, sayHello }; }, }; </script>
|
2. ref
Demo 2: Modification failure
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| <template> <h1>一个人的信息</h1> <h2>姓名: {{ name }}</h2> <h2>年龄: {{ age }}</h2> <button @click="changeInfo">修改人的信息</button> </template>
<script> export default { name: "App", setup() { let name = "张三"; let age = 18;
function changeInfo() { name = "李四"; age = 48; console.log(name, age); } return { name, age, changeInfo }; }, }; </script>
|
Demo 2: Correct way to modify
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| <template> <h1>一个人的信息</h1> <h2>姓名: {{ name }}</h2> <h2>年龄: {{ age }}</h2> <button @click="changeInfo">修改人的信息</button> </template>
<script> import { ref } from "vue"; export default { name: "App", setup() { let name = ref("张三"); let age = ref(18);
function changeInfo() { name.value = "李四"; age.value = 48; } return { name, age, changeInfo }; }, }; </script>
|
Demo 3: ref Object Type;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| <template> <h1>一个人的信息</h1> <h2>姓名: {{ name }}</h2> <h2>年龄: {{ age }}</h2> <h2>类型: {{ job.type }}</h2> <h2>薪资: {{ job.salary }}</h2> <button @click="changeInfo">修改人的信息</button> </template>
<script> import { ref } from "vue"; export default { name: "App", setup() { let name = ref("张三"); let age = ref(18); let job = ref({ type: "前端工程师", salary: "30K", });
function changeInfo() { name.value = "李四"; age.value = 48; job.value.type = "UI设计师"; job.value.salary = "60K"; } return { name, age, changeInfo, job }; }, }; </script>
|
3. reactivate
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| <template> <h1>一个人的信息</h1> <h2>姓名: {{ name }}</h2> <h2>年龄: {{ age }}</h2> <h2>类型: {{ job.type }}</h2> <h2>薪资: {{ job.salary }}</h2> <button @click="changeInfo">修改人的信息</button> </template>
<script> import { reactive, ref } from "vue"; export default { name: "App", setup() { let name = ref("张三"); let age = ref(18); let job = reactive({ type: "前端工程师", salary: "30K", });
function changeInfo() { name.value = "李四"; age.value = 48; job.type = "UI设计师"; job.salary = "60K"; } return { name, age, changeInfo, job }; }, }; </script>
|