| <div id="app"> |
| 姓:<input type="text" v-model="firstName"><br /><br /> |
| 名:<input type="text" v-model="lastName"><br /><br /> |
| 全名:<span></span> |
| </div> |
| <script type="text/javascript"> |
| const vm = new Vue({ |
| el: '#app', |
| data: { |
| firstName: '张', |
| lastName: '三' |
| }, |
| computed: { |
| fullName: { |
| |
| |
| get() { |
| |
| return this.firstName + this.lastName |
| } |
| } |
| }, |
| methods: { |
| } |
| }) |
| </script> |
计算属性中 get 函数和 set 函数
| <div id="app"> |
| 姓:<input type="text" v-model="firstName"><br /><br /> |
| 名:<input type="text" v-model="lastName"><br /><br /> |
| 全名:<span></span> |
| </div> |
| <script type="text/javascript"> |
| const vm = new Vue({ |
| el: '#app', |
| data: { |
| firstName: '张', |
| lastName: '三' |
| }, |
| computed: { |
| fullName: { |
| |
| |
| |
| get() { |
| |
| return this.firstName + this.lastName |
| }, |
| |
| set(value) { |
| console.log('接收到的修改的值', value); |
| const arr = value.split('-'); |
| this.firstName = arr[0]; |
| this.lastName = arr[1]; |
| } |
| } |
| }, |
| methods: {} |
| }) |
| </script> |
计算属性的优势,与 methods 实现相比,内部有缓存机制(复用),效率更高
计算属性的简写:
| <div id="app"> |
| 姓:<input type="text" v-model="firstName"><br /><br /> |
| 名:<input type="text" v-model="lastName"><br /><br /> |
| 全名:<span></span> |
| </div> |
| <script type="text/javascript"> |
| const vm = new Vue({ |
| el: '#app', |
| data: { |
| firstName: '张', |
| lastName: '三' |
| }, |
| |
| computed: { |
| fullName() { |
| return this.firstName + this.lastName; |
| } |
| }, |
| }) |
| </script> |