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

时间:2018-09-13 13:31:38

标签: javascript vue.js vuejs2

如果我的搜索输入中包含任何文本,我只会显示覆盖图。

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

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:无法读取未定义的属性'length'”

我在这里做什么错了?

2 个答案:

答案 0 :(得分:2)

$root是树中最顶层的组件(用new Vue()实例化的组件),我不认为是Input.vue

无论如何,如果Input.vue 根组件,那么按原样访问该组件的状态很麻烦。如果要跨组件共享数据,则应通过prop(从父级到子级的数据流)进行共享,或者在更复杂的情况下,可能需要共享数据存储区(例如Vuex)。

答案 1 :(得分:1)

永远不要访问这样的组件数据。那是一个坏方法。您应该看看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>