KingKongFrog
KingKongFrog

Reputation: 14419

Understanding of vue-router and data properties

I have a situation where when I navigate to a route, my computed property updates and updates my view accordingly. When I switch to another route and back - I lose all my data that is assigned in the this scope. I'm using created to initialize these variables, and then navigate back they reinitialize to a null state.

In my computed property, I populate these other (created variables) and those are used in the view.

My question is - is the reinitializing normal? Am I going about this incorrectly?

    created: function() {
            this.abc = {};
    },
    computed: {
        myData: function() {
            return this.$store.state.myData;
        },
        setupData: function() {
            console.log('only update now!')
            var myData = this.myData;

            //doSomething that updates this.abc
        }
     },
     watch: {
        myData: {
            handler: function(newValue) {
                this.setupData(newValue);
            },
            deep: true
        }
    },

Upvotes: 1

Views: 80

Answers (1)

cello
cello

Reputation: 5486

Yes, the re-initialization is normal. If you want to keep your component, use the keep-alive tag:

If you want to keep the switched-out components in memory so that you can preserve their state or avoid re-rendering, you can wrap a dynamic component in a element:

<keep-alive>
  <component :is="currentView">
    <!-- inactive components will be cached! -->
  </component>
</keep-alive>

The documentation about the <router-view> also refers to it:

Since it's just a component, it works with <transition> and <keep-alive>.

Upvotes: 3

Related Questions