6

What is the proper way to override methods using mixins in Vue.js? I know that you're able to mock inheritance using mixins, but let's say that you want to extend some props but not completely override the entire prop value.

For instance I have a baseCell, but I also need to have components that will be similar but function differently for <td>s and <th>s, so I create two additional components that use the baseCell as the mixin.

var baseCell = {
  ...
  props: {
    ...
    initWrapper: {
      type: String,
      default: 'td'
    },
    ...
  },
  methods: {..}
};

In the components setting the props as such will completely override all the values.

Vue.component('tableHeader', {
  mixins: [baseCell],
  props: {
    initWrapper: {
      default: 'th'
    }
  }
}

I've come up with a solution of merging the properties but it seems sort of hacky, and I'm not sure if there is a better solution.

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

With this, I retain the baseCell props, but some defined ones in the object passed.

4
  • 2
    The documentation vuejs.org/v2/guide/mixins.html#Option-Merging clearly states that that the component will take precendence on merges. As a result, your solution seems quite reasonable. Commented Nov 16, 2016 at 19:52
  • @DavidL Thank you for looking at the question. I had seen that part of the docs but only glanced over it. Your comment made me dig a little deeper into the source and as a result I found this issue that addresses the question of merging data and props... github.com/vuejs/vue/issues/2897 It looks like the current solution is to do it as I currently am. Commented Nov 16, 2016 at 20:31
  • 1
    Agreed, based on that issue it definitely would seem like you picked the right solution. Happy to help :) Commented Nov 16, 2016 at 20:32
  • What about using extends instead of mixins? I can still pass the original props. Commented Aug 9, 2017 at 13:01

1 Answer 1

1

In Vue > 2.2 you can use custom option merge strategies to achieve what you want. Note that the strategy applies to all mixins.

An example can be found here in the docu: https://v2.vuejs.org/v2/guide/mixins.html#Custom-Option-Merge-Strategies

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.