首页 > 解决方案 > 将计算的 setter 编写为公共函数

问题描述

我在 vue 中遇到了Computed setter,我发现它非常有用。为了完整起见,我将在此处复制并粘贴代码片段。

// ...
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]
    }
  }
}
// ...

这在我的情况下非常有效。唯一的问题是在几个组件上有相同的块,我不太喜欢这样。我更喜欢定义一个类似的方法GetOrSetFullName(newValue),然后在组件中简单地调用类似的方法

// ...
computed: {
  fullName: GetOrSetFullName(newValue);
}
// ...

这是否可能,或者是否有其他标准化程序来避免多个组件上的重复代码块?

注意:以防万一。上面的代码是从 vue 网页复制粘贴的,但我使用的是打字稿。

标签: typescriptvue.jsmethods

解决方案


您可以在单独的对象中定义 getter/setter 并将其重用于您的心脏内容:

const fullNameComputer = {
  get: function() {
    return this.firstName + ' ' + this.lastName;
  },
  set: function(value) {
    var names = value.split(' ');
    this.firstName = names[0];
    this.lastName = names[names.length - 1];
  }
};

const app = new Vue({
  el: '#app',
  data: {
    firstName: 'Foo',
    lastName: 'Bar'
  },
  computed: {
    fullName: fullNameComputer
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12"></script>

<div id="app">
  <input v-model.lazy="fullName">
  <br>
  {{ fullName }}
</div>


推荐阅读