
我们有一个需要多个组件共享的数据,单独放到一个组件中,其他组件需要使用,如果我们自己来完成这是非常麻烦的事情,你需要去写很多个组件通信的方法。Vuejs提供一个状态管理的插件Vuex。
上图就是Vuex的基本原理。我们将需要共享的数据存放到state(状态)中。
// 存放状态 state: { //状态是响应式 前提是属性都已经在state定义 counter: 1000, students: [ { id: 0, name: "c", age: 21, a: true }, { id: 0, name: "c", age: 18, a: true }, { id: 0, name: "c", age: 17, a: false }, { id: 0, name: "c", age: 20, a: false }, { id: 0, name: "c", age: 21, a: true }, ], arr: ["a", "a", "b", "b", "c", "c", "c"], age: null, info: { name: 'c', height: '186', age: 21 } },
通过render到组件中进行渲染。其实就是一个全局的store变量。在main.js中引入并加入Vue实例中。
//main.js import store from './store' new Vue({ store, render: h => h(App) }).$mount('#app')
当需要使用存放在state中的数据时,我们只需要
<h2>{{ $store.state.counter }}</h2> //或者 computed: { counter(){ return this.$store.state.couter } }
通过commit调用mutation对state进行操作 vuex中状态的更新唯一方式 mutation mutation中不能执行异步操作,mutation执行异步操作,虽然可以更改状态,但是Vue不能对其进行追踪
通过commit调用mutation对state进行操作
vuex中状态的更新唯一方式 mutation
mutation中不能执行异步操作,mutation执行异步操作,虽然可以更改状态,但是Vue不能对其进行追踪