Vue组件错误:属性或方法X未在实例上定义,但在渲染期间被引用

时间:2018-10-23 02:33:58

标签: vue.js

我有一个非常简单的设置,但由于以下错误而失败:

  

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

     

渲染错误:“ TypeError:无法读取未定义的属性'name'”

     

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

不确定是否是因为x模板引用方法有问题。我看到它用不了很多。

这是我的代码:

let slideshow_divs = ["container1", "container2", "container3"];
    for(let i = 1; i < slideshow_divs.length; i++) {
    document.getElementById(slideshow_divs[i]).style.display = "none";
}

let current_view = 0;

function clicky() {
    document.getElementById(slideshow_divs[current_view]).style.display = "none";

    if (current_view < slideshow_divs.length) {
        current_view = current_view + 1;
    } else {
        current_view = 0;
    }

    document.getElementById(slideshow_divs[current_view]).style.display = "block";
}

我想念什么? (我希望在屏幕上看到“香蕉”。)

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

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

将模板移至#main外部将允许其用作<my-thing>的模板,而无需呈现在#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