【问题标题】:Vue component error: Property or method X is not defined on the instance but referenced during renderVue 组件错误:属性或方法 X 未在实例上定义,但在渲染期间引用
【发布时间】:2019-03-27 04:16:33
【问题描述】:

我有一个相当简单的设置,但由于这些错误而失败:

属性或方法“fruit”未在实例上定义,但 在渲染期间引用。确保此属性是反应性的 [等等]

渲染错误:“TypeError:无法读取未定义的属性‘名称’”

无法读取未定义的属性“名称”

不确定是否是因为 x-template 引用方法有问题。我看用的不多。

这是我的代码:

<div id="main">

  <h1>Vue Component Prop Error</h1>

    <script type="text/x-template" id="foo">
      <p>{{fruit.name}}</p>
    </script>

    <my-thing :fruit="fruits[1]"></my-thing>

</div>

<script>
    Vue.component('my-thing', {
      template: '#foo',
      props: {
        fruit: Object
      }
    });

    var app = new Vue({
      el: '#main',
      data: {
        fruits: [{
            id: 1,
            name: 'apple'
        },{
            id: 2,
            name: 'banana'
        },{
            id: 3,
            name: 'carrot'
        }]
      }
    })
</script>

我错过了什么? (我希望在屏幕上看到“香蕉”。)

Codepen:https://codepen.io/MSCAU/pen/WagOjz

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    x-template移出主Vue实例控制的div

    <div id="main">
    
      <h1>Vue Component Prop Error</h1>
    
      <my-thing :fruit="fruits[1]"></my-thing>
    
    </div>
    
    <script type="text/x-template" id="foo">
      <p>{{fruit.name}}</p>
    </script>
    

    https://codepen.io/anon/pen/zmJzJO

    【讨论】:

      【解决方案2】:

      在 #main 中包含模板会导致 Vue 在您需要之前尝试渲染它。

      将模板移到#main 之外将允许它用作&lt;my-thing&gt; 的模板,而不会在#main 内部呈现。

      <div id="main">
          <my-thing :fruit="fruits[1]"></my-thing>
      </div>
      <script type="text/x-template" id="foo">
        <p>{{fruit.name}}</p>
      </script>
      

      https://codepen.io/anon/pen/NOLgBz

      【讨论】:

      • 同时提供两个好答案。这行得通,谢谢。现在这到底是在哪里记录的?此处未提及:vuejs.org/v2/guide/components-edge-cases.html#Inline-Templates
      • 好问题,不确定是否有专门的记录。这只是我从经验中知道的事情,也是你应该期待的事情。您将“el”设置为“#main”。因此,#main 内的任何内容都将使用app 范围进行渲染。 app 不知道您已将该块定义为 &lt;my-thing&gt; 的模板,或者它不应该尝试评估 {{ fruit.name }}
      猜你喜欢
      • 2018-07-24
      • 2021-05-04
      • 2019-05-05
      • 2019-03-30
      • 2022-01-04
      • 2019-07-20
      • 2019-02-20
      • 2021-11-27
      相关资源
      最近更新 更多