简体   繁体   English

在 Vue.js 中保持组件存活

[英]Keep component alive in Vue.js

I am using the Creative-Tim Dashboard to develop a small application and I realize the components loaded on each page are destroyed and re-created each time I switch pages from the sidebar.我正在使用 Creative-Tim Dashboard开发一个小型应用程序,我意识到每次从侧边栏切换页面时,每个页面上加载的组件都会被销毁并重新创建。

I use a global Vue Mixin to my application to send and receive MQTT messages.我在我的应用程序中使用全局 Vue Mixin 来发送和接收 MQTT 消息。 The methods created and beforeDestroy are called each time I switch panels.每次切换面板时都会调用createdbeforeDestroy方法。

Is there a way to:有没有办法:

  • Keep my Mixin alive让我的 Mixin 保持活力
  • Keep my components data alive让我的组件数据保持活力

As an example one of my component is a MQTT Widget:例如,我的组件之一是 MQTT 小部件:

<template>
  <Widget :title="title" :subtitle="subtitle" :footer="topic">
      <h1>{{value}}</h1>
  </Widget>
</template>
<script>

import Widget from './Widget.vue'

export default {
  name: 'numeric-widget',
  components: {
    Widget
  },
  props: {
    title: String,
    subtitle: String,   
    topic: String,
    unit: String
  },
  data () {
    return {
      value: '--'
    }
  },
  mounted () {
    // Subscribe method is exposed by a global Vue Mixin
    this.subscribe(this.topic, (topic, payload) => {
      this.value = payload
    })
  }
}
</script>

Here what happens:这里会发生什么:

  1. Load the page (seeing -- )加载页面(看到--
  2. Receive a MQTT value (seeing `80 bpm')接收一个 MQTT 值(看到“80 bpm”)
  3. Switching to another page切换到另一个页面
  4. Method beforeDestroy of my Mixin is called我的 Mixin 的beforeDestroy方法被调用
  5. Switching back to the dashboard切换回仪表板
  6. Method created of my Mixin is called我的 Mixin created的方法被称为
  7. I see -- as if I never received any message.我明白了--好像我从未收到任何消息。

I have seen on many question that using <keep-alive> may help.我在许多问题上看到使用<keep-alive>可能会有所帮助。 Unfortunately it does not seem to work in my case.不幸的是,它似乎不适用于我的情况。

I think you can use我认为你可以使用tag if you don't want your components to be destroyed and recreated again.如果您不希望您的组件被销毁并再次重新创建,请标记。 Following links might help.以下链接可能会有所帮助。

vue js docs keep alive vue js 文档保持活力

vue js keep alive vue js保持活力

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM