在外部更改数据时,vue组件不会更新

时间:2017-11-18 11:57:55

标签: vue.js vue-component

当Store.loaded更改时,我的组件不会更新已加载的属性:

组件

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
}

存储

class Root {
    loaded = false
}

export let Store = new Root()
export default Store

1 个答案:

答案 0 :(得分:2)

在您的示例中,// Update one field, creating the document if it does not already exist. Map<String, Object> data = new HashMap<>(); data.put("Visitor.NOTIFY_ON_CHAT_MESSAGE", true); docRefVisitor.set(data, SetOptions.merge()); 只是普通函数(类),没有任何反应性(Store字段没有附加Vue观察者)。

只有组件Store.loaded内的属性才具有反应性。如果您希望在vue组件之外使用被动单一存储(对于大型前端应用程序更好),您应该使用Vuex

简单的例子是:

<强> App.vue:

data

<强>部件/ ChildComponent.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>

反应性Vuex商店:

商品/ index.js:

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

您可以找到此示例的完整来源on GitHub