在 Vue.js 中覆盖属性和方法的正确方法?

kyl*_*yle 6 javascript vue.js vuejs2

在 Vue.js 中使用mixin覆盖方法的正确方法是什么?我知道您可以使用 mixin 来模拟继承,但是假设您想扩展一些 props 但不完全覆盖整个 prop 值。

例如,我有一个 baseCell,但我还需要有类似的组件,但对于<td>s 和<th>s 的功能不同,所以我创建了两个额外的组件,它们使用 baseCell 作为 mixin。

var baseCell = {
  ...
  props: {
    ...
    initWrapper: {
      type: String,
      default: 'td'
    },
    ...
  },
  methods: {..}
};
Run Code Online (Sandbox Code Playgroud)

在组件中设置道具将完全覆盖所有值。

Vue.component('tableHeader', {
  mixins: [baseCell],
  props: {
    initWrapper: {
      default: 'th'
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我想出了一个合并属性的解决方案,但似乎有点笨拙,我不确定是否有更好的解决方案。

Vue.component('tableHeader', {
  mixins: [baseCell],
  props: Object.assign({}, baseCell.props, {
    initWrapper: {
      default: 'th'
    }
  })
});
Run Code Online (Sandbox Code Playgroud)

有了这个,我保留了 baseCell 道具,但传递了对象中的一些定义的道具。

小智 1

在 Vue > 2.2 中,您可以使用自定义选项合并策略来实现您想要的。请注意,该策略适用于所有 mixin。

可以在文档中找到示例: https: //v2.vuejs.org/v2/guide/mixins.html#Custom-Option-Merge-Strategies