【问题标题】:Vuejs mounted hook in component not working as expected组件中的 Vuejs 挂载钩子未按预期工作
【发布时间】:2019-07-27 19:36:12
【问题描述】:

我在组件中使用挂载的钩子,并希望在仪表板视图上加载图表,如下所示。

仪表板脚本

export default {
    name: 'Dashboard',
    mounted() {

        console.log(this.$el); //--> console output -> empty
        const self = this;
        this.$nextTick(function () {
            // some init codes for chart implementation
            console.log(self.$el); //--> console output -> empty also.
        }
    }
}

我有一个 App.vue 文件用作容器。它具有默认的模板结构(我的意思是没有什么特别的)。 如何理解组件加载?

我认为; mounted() 钩子在 App.vue 加载时触发。但此时仍未创建仪表板组件 DOM。所以我决定使用nextTick 事件。但它也像mounted() 钩子。我有点困惑。

编辑:这个问题是在键盘上按下F5 按钮时引起的。

编辑 2: 应用程序.vue

<template>
    <section id="app" class="container-fluid">
        <div class="content">
            <router-view />
        </div>
    </section>
</template>

路由器.js

import Vue from 'vue'
import Router from 'vue-router'
import Dashboard from './views/Dashboard.vue'

Vue.use(Router)

export default new Router({
  mode: 'history',
  routes: [
    { path: '/', component: Dashboard }
  ]
})

【问题讨论】:

  • 子组件注册了吗?能否提供该组件和父组件的完整代码
  • @mooga 用代码块编辑了我的问题。

标签: javascript vue.js vuejs2 vue-component


【解决方案1】:

nextTick 函数中的this 不是 Vue 组件。 您可以尝试使用箭头功能

this.$nextTick(() => {
    // some init codes for chart implementation
    console.log(this.$el); 
}

或关闭:

var self = this
this.$nextTick(() => {
    // some init codes for chart implementation
    console.log(self.$el); 
}

【讨论】:

  • 哦,谢谢指正。但它在nextTick 中仍然为空。
  • 你的 Vue 组件中有&lt;template&gt; 标签吗?
  • 绝对是的。如果不存在,则组件不起作用。
猜你喜欢
  • 2019-12-25
  • 1970-01-01
  • 2021-11-03
  • 1970-01-01
  • 2020-01-03
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多