Skip to content
Advertisement

Vue.js component: Props as object doesn’t work with x-template

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

  • postComponent should refer to template with a selector, so #post-template instead of post-template

Here’s a demo of it working: https://jsfiddle.net/vzj5g2sn/

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement