vue component does not update when data is changed

2019-06-11 02:52发布

My component does not update the loaded property when Store.loaded changes:

Component

import { Vue } from 'vue-property-decorator'
import Component from 'nuxt-class-component'
import { Store } from '../repositories'

@Component
export default class Layout extends Vue {
    loaded = Store.loaded
}

Store

class Root {
    loaded = false
}

export let Store = new Root()
export default Store

1条回答
【Aperson】
2楼-- · 2019-06-11 02:59

In your example Store is just plain function (class), without any reactivity (no Vue watchers attached for Store.loaded field).

Only properties inside component's data are reactive. If you want reactive single store outside of vue components (better for big frontend applications), you should use Vuex

Simple example will be:

App.vue:

<script>
import { mapGetters, mapMutations } from 'vuex';
import store from './store';
import ChildComponent from './components/ChildComponent.vue';

export default {
  store,
  components: { ChildComponent },

  methods: {
    ...mapMutations(['toggleLoaded']),
  },

  computed: {
    ...mapGetters({
      isLoaded: 'isLoaded',
    }),
  }
}

</script>

<template>
  <div id="app">
    <a href="javascript:" @click="toggleLoaded">Toggle loaded</a>

    <h3>Root component: </h3>
    <div>The loaded flag is: {{ isLoaded }}</div>

    <ChildComponent />
  </div>
</template>

components/ChildComponent.vue:

<script>
import { mapGetters } from 'vuex';

export default {
  computed: {
    ...mapGetters({
      isLoaded: 'isLoaded', //accessing to same data, as root through single Vuex state
    }),
  }
}
</script>

<template>
  <div class="hello">
    <h3>Child component</h3>
    <div>The loaded flag is: {{ isLoaded }}</div>
  </div>
</template>

And reactive Vuex store:

store/index.js:

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const state = {
  loaded: false
};

const getters = {
  isLoaded: state => state.loaded,
};

const mutations = {
  toggleLoaded: (state) => {
    state.loaded = !state.loaded;
  }
};

export default new Vuex.Store({
  state,
  mutations,
  // actions,
  getters,
  strict: true
});

You can find full source of this example on GitHub.

查看更多
登录 后发表回答