Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to override properties and methods in Vue.js?

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.

like image 572
kyle Avatar asked Nov 16 '16 18:11

kyle


People also ask

How do you manipulate props in Vue?

To specify the type of prop you want to use in Vue, you will use an object instead of an array. You'll use the name of the property as the key of each property, and the type as the value. If the type of the data passed does not match the prop type, Vue sends an alert (in development mode) in the console with a warning.

How can you prevent layout jumps in VUE JS?

Use single file components if you can. If you come from React you can also find jsx for Vue useful, or even write render function by hand (though not recommended). If you want to totally nullify the time of the first rendering though, the only way to go is to do server-side rendering.

Should always be multi word Vuejs?

User component names should always be multi-word, except for root App components. This prevents conflicts with existing and future HTML elements, since all HTML elements are a single word.

How do I switch between Vue components?

Each component can be linked by using props to pass the methods which will switch the components on triggering a certain event. Here is an example: HTML. CSS.


1 Answers

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

like image 77
Valentin Rapp Avatar answered Oct 14 '22 23:10

Valentin Rapp