Vue JS,无法读取属性$ el

时间:2019-04-15 08:13:00

标签: vuejs2 vue-component

我对正确理解流程元素(在vue js中调用方法)存在问题。这是标准的想法-从rest api获取一些数据,并在浏览器中呈现它们。

我写到mounted()中的geting方法。我还在那里添加了呼叫renderHomePageMethod()。此方法是用methods:

编写的
 mounted() {
    axios.get("http://localhost:3000/api/test").then(response => {
      this.testData= response.data
      this.renderHomePageMethod();
    });
  }

renderHomePageMethod()中,我使用了this.refs$$el。可能是有问题,一切正常,但是在浏览器中我得到了警告:

Uncaught (in promise) TypeError: Cannot read property '$el' of undefined

可能我应该打电话

this.renderHomePageMethod()

在另一个地方。但是在哪里?

1 个答案:

答案 0 :(得分:1)

似乎在主组件渲染之前未渲染您引用的组件,因此它给出了参考错误。

一种骇人听闻的方式将是这样的:

mounted() {
    axios.get("http://localhost:3000/api/test").then(response => {
        this.testData= response.data
        setTimeout(() => {
            this.renderHomePageMethod();
        }, 1000); // or any other minimum delay before the subcomponent is rendered
    });
}

或者通过更好和更困难的方法,创建一个包含以下内容的event-bus.js文件:

import Vue from 'vue';
export const EventBus = new Vue();

在主组件和子组件中:

import { EventBus } from "./event-bus.js";

在您的子组件中,它将在准备好滚动时将通知发送到主组件:

mounted(){
    EventBus.$emit("subcomponent:is-mounted");
}

在您的主要组件中:

data(){
    return {
       testData: null
    }
},
mounted(){
   axios.get("http://localhost:3000/api/test").then(response => {
       this.testData= response.data
   });
   EventBus.$on("subcomponent:is-mounted", () =>{
       this.renderHomePageMethod();
   });
},
beforeDestroy(){
   EventBus.$off("subcomponent:is-mounted");
   // don't forget to remove the listeners because of duplicate listeners may occur 
   // if your component refreshes (remounts)
}
相关问题