To simplify the markup of a Vue component, I’m trying to use an object for the props.
When defining the template of the component as described in the code example on Components Basics — Vue.js all works fine. But trying to define the template as an x-template, I’m getting an error saying, that the property ‘title’ of undefined cannot be read.
Here’s the code:
<div id="app">
<script type="text/x-template" id="post-template">
<div class="blog-post">
<h3>{{ post.title }}</h3>
<div v-html="post.content"></div>
</div>
</script>
<blog-post v-for="post in posts" v-bind:key="post.id" v-bind:post="post"></blog-post>
</div>
const data = {
posts: [
{
title: "Hello World",
content: "Bar"
}
]
};
let postComponent = {
props: ['post'],
template: 'post-template'
}
const vue = new Vue({
el: '#app',
components: {
'blog-post': postComponent
},
data() {
return data;
}
});
Is it not possible to access object properties in a x-template or is there something wrong with my code?
Advertisement
Answer
Two things:
Take the x-template outside of your app div. Vue is going to replace all the content in the div, so that template will be lost
postComponentshould refer totemplatewith a selector, so#post-templateinstead ofpost-template
Here’s a demo of it working: https://jsfiddle.net/vzj5g2sn/