Karl
Karl

Reputation: 87

Passing data to root Vue class component

I have a component defined using Vue class components like so:

@Component
export default class MyComponent extends Vue {
  value = 0;
}

I need to repeatedly instantiate this component as a root component with different data passed in each time. For example, I've tried doing this:

const vm = new Vue({
  el: myElement,
  render: (h) => h(MyComponent),
  data: {value: 1},
});

But when I look at this.value in the component it is set to 0 instead of 1. Is there anyway for me to specify that I'd like the component to be instantiated with the value passed in when calling new Vue?

Upvotes: 3

Views: 328

Answers (1)

Decade Moon
Decade Moon

Reputation: 34286

What you tried doesn't work because your root component is rendering MyComponent as a child component and the data defined in the root component is separate to the data of the child. They're two distinct components, there's no overriding here.

I'm not familiar with Vue class components, but here's a vanilla solution. The MyComponent class extends Vue, so you can instantiate MyComponent directly as the root component, and any additional options you provide during its instantiation will be mixed in to the base options.

So you only need to do something like this instead:

const vm = new MyComponent({
  el: myElement,
  data: { value: 1 },
})

No need to specify the render function because it is defined already by MyComponent.

Here's a runnable snippet that demonstrates what I mean:

const MyComponent = Vue.extend({
  template: '<div>{{ value }}</div>',
  data() {
    return {
      value: 'base'
    }
  }
})

new MyComponent({
  el: '#app',
  data: {
    value: 'extended'
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>

Upvotes: 1

Related Questions