es6 计算属性的原理(get和set)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>计算属性</title> <script src="./vue2.6.9.js"></script> </head> <body> <div id="app"> <h1>{{fullName}}</h1> </div> <script> var vm = new Vue({ el: '#app', data: { firstName: 'ma', lastName: 'long' }, //计算属性一般是没有set方法的,只有只读属性 computed: { fullName: { set:function(newValue){ const names =newValue.split(' ');//返回一个数组 this.firstName =names[0]; this.lastName =names[1]; console.log('set方法被调用----'+newValue) }, get: function () { return this.firstName + ' ' + this.lastName } } } }) </script> </body> </html>
效果图