源代码 :
点击运行
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Vue 测试实例 - 开源教程(ossoft.cn)</title> <script src="https://unpkg.com/vue@next"></script> </head> <body> <div id="app"> </div> <script> const app = { data() { return { name: 'Google', url: 'http://www.google.com' } }, computed: { site: { // getter get: function () { return this.name + ' ' + this.url }, // setter set: function (newValue) { var names = newValue.split(' ') this.name = names[0] this.url = names[names.length - 1] } } } } vm = Vue.createApp(app).mount('#app') document.write('name: ' + vm.name); document.write('<br>'); document.write('url: ' + vm.url); document.write('<br>------ 更新数据 ------<br>'); // 调用 setter, vm.name 和 vm.url 也会被对应更新 vm.site = '开源教程 '; document.write('name: ' + vm.name); document.write('<br>'); document.write('url: ' + vm.url); </script> </body> </html>
运行结果