【问题标题】:vue component does not update when data is changed external外部更改数据时vue组件不更新
【发布时间】:2017-11-18 11:57:55
【问题描述】:

我的组件在 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

【问题讨论】:

  • 您能否说明您在哪里以及为什么要在外部进行更改?
  • 例如store 包括一个用户属性和一个游戏数组。用户可以加入游戏 --> 用户有一个方法可以将游戏对象中的参与属性设置为 true。但是这种变化没有被采纳。 (我不得不提一下,当组件加载时,并不是所有的 store 属性都已经存在。--> 即游戏是动态加载的)

标签: vue.js vue-component


【解决方案1】:

在您的示例中,Store 只是普通函数(类),没有任何反应性(Store.loaded 字段没有附加 Vue 观察者)。

只有组件的 data 内的属性是响应式的。如果你想要 vue 组件之外的响应式单一存储(更适合大型前端应用程序),你应该使用Vuex

简单的例子是:

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>

以及响应式 Vuex 存储:

商店/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
});

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

【讨论】:

  • 我实际上目前正在使用 vuex 并且想重构它。调度/提交的麻烦以及由此导致的智能感知破坏超过了我的用例的好处。
  • &gt;intellisense - 如果您的意思是代码完成,您可以将操作/提交名称提取到常量。例如,参见shopping-cart-vuex-example中的mutation-types.js-file
  • &gt;hassle with dispatch/commit 我没有使用mobx-library 的经验,但我听说,它比redux 和vuex 更简单。也许您可以将它用作其他单一商店的模拟物。我也刚刚发现了这个项目:vue-mobx - 可能对你有用。
猜你喜欢
  • 1970-01-01
  • 2019-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-22
  • 1970-01-01
  • 2018-06-14
  • 2019-08-06
相关资源
最近更新 更多