nowox
nowox

Reputation: 29096

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.

I use a global Vue Mixin to my application to send and receive MQTT messages. The methods created and beforeDestroy are called each time I switch panels.

Is there a way to:

As an example one of my component is a MQTT Widget:

<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')
  3. Switching to another page
  4. Method beforeDestroy of my Mixin is called
  5. Switching back to the dashboard
  6. Method created of my Mixin is called
  7. I see -- as if I never received any message.

I have seen on many question that using <keep-alive> may help. Unfortunately it does not seem to work in my case.

Upvotes: 4

Views: 5766

Answers (1)

Pallamolla Sai
Pallamolla Sai

Reputation: 2493

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 keep alive

Upvotes: 2

Related Questions