vue-计算属性get和set
一、计算属性get和set
计算属性由两部分组成,get和set。默认只有get。get和set的功能说明如下:
- get:获取计算属性。
- set:设置计算属性。
二、代码实现
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>vue计算属性</title> 6 <!--引入vue--> 7 <script src="../js/vue.js"></script> 8 9 </head> 10 <body> 11 <div id="hello"> 12 <!-- 计算属性 --> 13 <h3>计算属性返回num2:{{num2}}</h3> 14 <button @click='change'>修改num2的值</button> 15 </div> 16 17 <script> 18 let vm = new Vue({ 19 //vue挂载目标 20 el:'#hello', 21 //vue属性 22 data:{ //普通属性 23 num:9 24 }, 25 26 //vue计算属性 27 computed:{ //计算属性 28 num2:{ 29 get:function(){ //get函数 30 console.log('get函数,根据num获取num2的值'); 31 return this.num-1; 32 }, 33 set:function(val){ //set函数 34 console.log('set函数,设置num新值获取num2新值') 35 this.num=800; 36 } 37 } 38 }, 39 40 //vue方法 41 methods:{ 42 change(){ 43 console.log('点击按钮调用change方法') 44 //在change方法中给num2赋值,就会触发调用num2中的set函数 45 this.num2=200 46 } 47 }, 48 }) 49 50 </script> 51 52 </body> 53 </html>
三、效果展示