重新学习Vue_01_watch computed

走远了吗. 提交于 2019-11-28 13:50:47
 1 <template>
 2     <div>
 3         <label>姓:<input type="text" placeholder="请输入姓氏" v-model="firstName"></label>
 4         <p></p>
 5         <label>名:<input type="text" placeholder="请输入名字" v-model="lastName"></label>
 6 
 7         <p>-----------------------------------------------------------------------</p>
 8         <!--单向-->
 9         <label>姓 名:<input type="text" placeholder="请输入姓名" v-model="fullNameOne"></label>
10         <p></p>
11         <!--双向-->
12         <label>姓 名:<input type="text" placeholder="请输入姓名" v-model="fullNameTwo"></label>
13         <p></p>
14         <!--双向-->
15         <label>姓 名:<input type="text" placeholder="请输入姓名" v-model="fullNameThree"></label>
16     </div>
17 </template>
18 
19 <script>
20     export default {
21         name: "ComputedAndWatch",
22         data(){
23             return {
24                 firstName: '', // 姓
25                 lastName: '', // 名
26                 // 被watch监听改变
27                 fullNameThree: ''
28             }
29         },
30         // 配置计算属性
31         computed: {
32             // 计算属性 姓名
33             fullNameOne: {
34                get(){
35                    return this.firstName + '·' + this.lastName
36                }
37             },
38 
39             fullNameTwo: {
40                 get(){
41                    // console.log(`调用了fullNameTwo的getter方法`);
42                    return this.firstName + '·' + this.lastName;
43                 },
44                 set(value){
45                     // console.log(`调用了fullNameTwo的setter方法, 值:${value}`);
46                     // 1.更新firstName和lastName
47                     let names = value.split('·');
48                     console.log(names);
49                     this.firstName = names[0];
50                     this.lastName = names[1];
51                 }
52             }
53         },
54         // 配置watch
55         watch: {
56             // 监听firstName
57             firstName(value){
58                 console.log(`watch监视到firstName发生改变:${value}`);
59                 // 更新fullNameThree
60                 this.fullNameThree = value + '·' + this.lastName;
61             },
62 
63             // 监听lastName
64             lastName(value){
65                 console.log(`watch监视到lastName发生改变:${value}`);
66                 // 更新fullNameThree
67                 this.fullNameThree = this.firstName + '·' + value;
68             }
69         }
70     }
71 </script>
72 
73 <style scoped>
74 
75 </style>

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!