Vue.js 教程

Vue.js 计算属性的 setter

前面介绍了计算属性的基本用法,也提到过,计算属性默认只有 getter,如果我们需要 setter 方法怎么办呢?Vue.js 允许我们手动指定 getter 和 setter 方法,例如:

var app = new Vue({
   el: "#app",
   data: {
       firstName: 'Foo',
       lastName: 'Bar',
       fullName: 'Foo Bar'
   },
   computed: {
       fullName: {
           // getter 方法
           get: function () {
               return this.firstName + ' ' + this.lastName
           },
           // setter 方法,参数 newValue 为新的值
           set: function (newValue) {
               var names = newValue.split(' ')
               this.firstName = names[0]
               this.lastName = names[names.length - 1]
           }
       }
   }
});

你可以打开浏览器的控制台,修改例子中的 app.fullName = 'John Doe' 时,setter 会被调用,app.firstName 和 app.lastName 也会相应地被更新。

完整示例

<html>
<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Vue</title>
   <!-- 使用 CDN 引入 Vue 库 -->
   <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>
<body>

   <div id="app">
       <div id="demo">{{ fullName }}</div>
   </div>

   <script type="text/javascript">
       var app = new Vue({
           el: "#app",
           data: {
               firstName: 'Foo',
               lastName: 'Bar'
           },
           computed: {
               fullName: {
                   // getter
                   get: function () {
                       return this.firstName + ' ' + this.lastName
                   },
                   // setter
                   set: function (newValue) {
                       var names = newValue.split(' ')
                       this.firstName = names[0]
                       this.lastName = names[names.length - 1]
                   }
               }
           }
       });
   </script>

</body>
</html>

运行效果图:

说说我的看法
全部评论(
没有评论
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号