<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="app"> {{fullName}} --- {{age}} 计算属性 </div> </body> <script type="text/javascript"> let vm = new Vue({ el: ‘#app‘, data: { firstName: ‘Dell‘, lastName: ‘Less‘, age: 20 }, // 计算属性, 缓存机制 computed: { //计算属性的getter和setter方法 //数据渲染时会自动调用get方法 fullName: { get: function () { return this.firstName +‘ ‘+ this.lastName }, //数据变化时自动调用set方法 //现在再运行 vm.fullName = ‘John Doe‘ 时,setter 会被调用,vm.firstName 和 vm.lastName 也会相应地被更新。 set: function(value) { let arr = value.split(‘ ‘) // 当fullName相关联的数据发生变化时相当于重新调用get方法 this.firstName = arr[0] this.lastName = arr[1] } } } }) </script> </html>
原文地址:https://www.cnblogs.com/JunLan/p/12418699.html
时间: 2024-10-05 23:54:24