vue 组件在外部更改数据时不会更新 [英] vue component does not update when data is changed external
问题描述
当 Store.loaded 更改时,我的组件不会更新加载的属性:
组件
import { Vue } from 'vue-property-decorator'从'nuxt-class-component'导入组件从'../repositories'导入{商店}@成分导出默认类布局扩展 Vue {加载 = Store.loaded}
商店
类根{加载 = 假}export let Store = new Root()导出默认商店
在你的例子中 Store
只是普通的函数(类),没有任何反应性(没有为 Store.js 附加 Vue 观察者.加载
字段).
只有组件的 data
中的属性是响应式的.如果你想要 vue 组件之外的反应式单一存储(更适合大型前端应用程序),你应该使用 Vuex
简单的例子是:
App.vue:
<模板><div id="应用程序"><a href="javascript:" @click="toggleLoaded">切换加载</a><h3>根组件:</h3><div>加载的标志是:{{ isLoaded }}</div><子组件/>
</模板>
components/ChildComponent.vue:
<模板><div class="你好"><h3>子组件</h3><div>加载的标志是:{{ isLoaded }}</div>
</模板>
和响应式 Vuex 存储:
store/index.js:
从'vue'导入Vue;从 'vuex' 导入 Vuex;Vue.use(Vuex);常量状态 = {加载:假};const 吸气剂 = {isLoaded: 状态 =>状态加载,};常量突变 = {切换加载:(状态)=>{state.loaded = !state.loaded;}};导出默认新 Vuex.Store({状态,突变,//动作,吸气剂,严格:真实});
您可以在 在 GitHub 上找到此示例的完整源代码.>
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
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.
这篇关于vue 组件在外部更改数据时不会更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!