【问题标题】:Vue inline-template with v-for - not defined带有 v-for 的 Vue 内联模板 - 未定义
【发布时间】:2017-11-24 21:02:01
【问题描述】:

我正在尝试学习 Vue 并尝试使用内联模板和 v-for 循环来实现一个简单的测试。

当我加载以下页面时,我收到以下错误并且没有内容呈现到屏幕上。

[Vue 警告]:实例上未定义属性或方法“posts” 但在渲染期间引用。确保声明反应数据 数据选项中的属性。

我是 Vue 的初学者,但我们将不胜感激。

<!DOCTYPE html>

<html>
    <head>
        <title>Vue Test</title>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

        <script src="http://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
        <script src="https://unpkg.com/vue@2.3.4/dist/vue.js"></script>
    </head>

    <body>
        <div id="vue-app" class="container">
            <post-list inline-template v-for="(post, index) in posts" :key="post.id">
                <div class="post">
                    <h1>{{ post.subject }}</h1>
                </div>
            </post-list>
        </div>

        <script>
            Vue.component('post-list', {
                data: function() {
                    return {
                        posts: [
                            { id: 0, subject: 'The first post subject' },
                            { id: 1, subject: 'The second post subject' }
                        ]
                    }
                }
            });

            new Vue({
                el: '#vue-app'
            });
        </script>
    </body>
</html>

谢谢。

【问题讨论】:

    标签: vue.js vuejs2 vue-component


    【解决方案1】:

    您的v-for 需要模板中。 inline-template 表示元素内部的所有内容都是模板。

    组件将使用其内部内容作为其模板

    v-for 不在里面,所以它试图迭代 post-list 组件在根 Vue 上寻找 posts 并且它不存在。

    此外,迭代根元素会导致多个根(这是不允许的),因此我将v-for 包装在div 中。

    Vue.component('post-list', {
      data: function() {
        return {
          posts: [{
              id: 0,
              subject: 'The first post subject'
            },
            {
              id: 1,
              subject: 'The second post subject'
            }
          ]
        }
      },
    
    });
    
    new Vue({
      el: '#vue-app'
    });
    <script src="https://unpkg.com/vue@2.2.6/dist/vue.js"></script>
    <div id="vue-app" class="container">
      <post-list inline-template>
        <div>
          <div class="post" v-for="(post, index) in posts" :key="post.id">
            <h1>{{ post.subject }}</h1>
          </div>
        </div>
      </post-list>
    </div>

    【讨论】:

      猜你喜欢
      • 2020-01-31
      • 2019-04-22
      • 2022-07-24
      • 2021-08-19
      • 2020-11-22
      • 1970-01-01
      • 2020-09-24
      • 2021-07-16
      • 2018-08-03
      相关资源
      最近更新 更多