【问题标题】:Error in render: "TypeError: Cannot read property 'length' of undefined"渲染错误:“TypeError:无法读取未定义的属性‘长度’”
【发布时间】:2019-02-18 06:06:15
【问题描述】:

如果我的搜索输入包含任何文本,我会尝试仅显示叠加层。

这是我的模板,我的输入字段是:

Input.vue:

<template>
    <div>
        <input v-model="query" class="input" placeholder="Global search..."></input>

    </div>
</template>
<script>
    export default {
        data() {
            return {
                query: '',
            };
        }
    };
</script>

当我签入控制台时,query 会更新我在输入字段中写入的任何文本。

然后我尝试将此变量传递给另一个组件,该组件包含我的叠加 div:

Overlay.vue:

<template>
    <div v-if="this.$root.query.length > 0">
        <div class="search-overlay is-active"></div>
    </div>
</template>

但是,这给了我以下错误:

[Vue 警告]:渲染错误:“TypeError: Cannot read property 'length' of undefined”

我在这里做错了什么?

【问题讨论】:

  • 为什么需要this.$root?您能否提供有关您的不同组件的更多详细信息?
  • 将您的query 对象作为您的覆盖组件的道具:&lt;overlay :query="query" /&gt; 并在您的Overlay.vue 中定义该道具。

标签: javascript vue.js vuejs2


【解决方案1】:

$root 是树中最顶层的组件(您使用 new Vue() 实例化的组件),我不相信它是 Input.vue

无论如何,如果Input.vue 根组件,那么访问组件的状态是很麻烦的。如果您想跨组件共享数据,您应该通过 props(从父级到子级的数据流)来实现,或者对于更复杂的情况,您可能需要共享数据存储(例如 Vuex)。

【讨论】:

    【解决方案2】:

    您永远不应该像这样访问组件数据。这是一个糟糕的方式。你应该看看 VueX 和状态管理模式,因为这是你在这里遇到的一个典型案例。

    但是,如果您不想使用 VueX(或其他用于状态管理模式的工具),您应该使用这样的事件:

    var Input = Vue.component('custom-input', {
      name : "custom-input",
      template : "#custom-input-template",
      props : ["value"],
      methods : {
        onInput(){    
          this.$emit('input', this.$refs.queryInput.value)
        }
      },
      created() {
        console.log("Custom-input created")
      }
    });
    
    var Overlay = Vue.component('custom-overlay', {
      name : "custom-overlay",
      template : "#custom-overlay-template",
      props : ["query"],
      created() {
        console.log("Custom-overlay created")
      }
    });
    
    new Vue({
        el: "#app",
        components : {
          Input,
          Overlay
        },
        data: {
    		  query : null
        }
    })
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <div id="app">
    	<div>		
    		 <custom-input v-model="query"></custom-input>
    		 <custom-overlay v-show="query && query.length > 0" :query="query"></custom-overlay>
    	</div>
    </div>
    
    
    <script type="text/x-template" id="custom-input-template">
        <div>
            <input :value="value" ref="queryInput" class="input" placeholder="Global search..." @input="onInput"></input>
        </div>
    </script>
    
    <script type="text/x-template" id="custom-overlay-template">
      <div>
    	  {{query}}
      </div>
    </script>

    【讨论】:

      猜你喜欢
      • 2021-10-25
      • 1970-01-01
      • 2021-07-20
      • 2020-01-19
      • 2019-11-24
      • 2021-02-26
      • 2021-02-17
      • 2020-04-08
      • 2022-01-13
      相关资源
      最近更新 更多