1、vuex是什么
公共状态管理
解决多个非父子组件传值问题。
多个页面都能用Vuex中store公共的数据
a、并不是所有的数据都要放在Vuex中,只有各个组件公用的一些数据会放在Vuex当中
b、Vuex是一个公共状态管理模式 并不是数据库 所以不可能持久保存一些数据
当用户刷新浏览器的时候那么数据就有可能消失
c、Vuex主要应用在大型的单页面开发中
2、vuex的特点
1、遵循单向数据流
2、Vuex中的数据是响应式的
3、vuex的流程图:
总结下vuex数据传输流程
1、通过new Vuex.Store()创建一个仓库 state是公共的状态,state—>components渲染页面
2、在组件内部通过this.$store.state.属性 来调用公共状态中的state,进行页面的渲染。
3、当组件需要修改数据的时候,必须遵循单向数据流。组件里在methods中扩展mapActions,调用store里的actions里的方法。
4、actions中的每个方法都会接受一个对象 这个对象里面有一个commit方法,用来触发mutations里面的方法
5、mutations里面的方法用来修改state中的数据 mutations里面的方法都会接收到2个参数 一个是store中的state, 另外一个是需要传递到参数
6、当mutations中的方法执行完毕后state会发生改变,因为vuex的数据是响应式的 所以组件的状态也会发生改变
**// store.js**
import Vue from 'vue'
import Vuex from 'vuex'
/* eslint-disable*/
Vue.use(Vuex)
export default new Vuex.Store({
state : { // 定义素有的状态参数
count:10
},
// 组建里面的 methods:{ 扩展MapActions 向store里面的action通知,使其用commit通知相应的mutaions里的方法,使其方法执行,更改状态。
// ...mapActions ([
// 'increment',
// 'decrement'
// ])
// }
actions :{
increment: ({commit}) => {
console.log('actions- commit--increment')
commit('increment')
},
decrement: ({commit}) => {
console.log('actions- commit-decrement')
commit('decrement')
}
},
mutations :{
increment (state) {
console.log('mutations---increment')
state.count++
},
decrement (state) {
console.log('mutations----decrement')
state.count--
}
},
getters : {
count(state) {
return state.count
}
}
})
// main.js
// 引入一堆
import Vue from 'vue'
import VueRouter from 'vue-router'
// 主体
import App from './components/app.vue'
import store from '@/store/store.js'
// 路由切换页面
import home from './components/home.vue'
// 安装插件
Vue.use(VueRouter) // 挂载属性
// 创建路由对象并配置路由规则
let router = new VueRouter({
// routes
routes: [{
path: '/',
components: {
default: home
}
}
]
})
/* eslint-disable no-new */
new Vue({
el: '#app',
store, // 将状态的store.js挂载在vue上
// 让vue知道我们的路由规则
router, // 可以简写router
render: c => c(App)
})
// home.vue
<template>
<div>
<input type="button" value="增加数量+++" @click="increment">
<input type="button" value="减少数量---" @click="decrement">
现在的数字是:{{$store.state.count}}
</div>
</template>
<script>
/* eslint-disable*/
import {mapGetters, mapActions } from 'vuex'
export default {
data () {
return {
msg: 'Welcome to YourHome'
}
},
computed: {
// 使用对象展开运算符将 getter 混入 computed 对象中
...mapGetters([
'count'
])
},
methods:{
...mapActions ([
'increment',
'decrement'
])
}
}
</script>