【问题标题】:Vue.js component: Props as object doesn’t work with x-templateVue.js 组件:作为对象的道具不适用于 x-template
【发布时间】:2020-12-02 14:46:05
【问题描述】:

为了简化 Vue 组件的标记,我尝试使用一个对象作为道具。

按照Components Basics — Vue.js 上的代码示例中所述定义组件的模板时,一切正常。但是尝试将模板定义为 x 模板时,我收到一条错误消息,即 undefined 的属性“标题”无法读取。

代码如下:

<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;
    }
});

无法访问x-template 中的对象属性还是我的代码有问题?

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component


    【解决方案1】:

    两件事:

    • 将 x-template 放在您的应用 div 之外。 vue会替换掉div里的所有内容,这样模板就丢失了

    • postComponent 应该使用选择器引用template,所以#post-template 而不是post-template

    这是它的工作演示:https://jsfiddle.net/vzj5g2sn/

    【讨论】:

    • 非常感谢。对我来说,将所有组件放在应用程序的容器中是很自然的。
    猜你喜欢
    • 2017-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 2023-04-08
    • 1970-01-01
    • 2017-04-30
    相关资源
    最近更新 更多