I have a single file component header.vue
:
<template>
<h1>{{text}}</h1>
</template>
<script>
export default {
data() {
return {
text: 'Header text',
};
},
};
</script>
I require it in my code as follows
const Header = require('components/header.vue');
And call it:
const header = new Vue({
el: '#header',
data: {
text: 'New header text',
},
render: h => h(Header),
});
The component is rendered, but the text says Header text
instead of New header text
. Why?
You have two separate components here, the Header component and the anonymous component you created (with new Vue()
). The anonymous component renders the Header component as its child. Both components have separate data
properties; the parent has text = 'New header text'
and the child has text = 'Header text'
.
There are two ways (off the top of my head) that you can achieve this:
text
data property with the new value:const Header = require('components/header.vue');
const HeaderComp = Vue.extend(Header);
const header = new HeaderComp({
el: '#header',
data: {
text: 'New header text',
},
});
text
a prop instead, you will be able to pass data down to the child from the parent:header.vue
<script>
export default {
props: ['text'],
};
</script>
usage
const Header = require('components/header.vue');
// Using render function
const header = new Vue({
el: '#header',
render: h => h(Header, {
props: {
text: 'New header text',
},
}),
});
// Using template
const header = new Vue({
el: '#header',
components: {
Header,
},
template: '<header text="New header text"/>',
});
I think there can be two ways to solve this:
To pass props you have to make following changes in header.vue
:
<script>
export default {
props: ['text'],
};
</script>
And call it:
const header = new Vue({
template: '<header :text="text" />',
data: {
text: 'New header text',
}
});
header
component.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With