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
?
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 extendsVue
, so you can instantiateMyComponent
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:
No need to specify the render function because it is defined already by
MyComponent
.Here's a runnable snippet that demonstrates what I mean: