使用vuex实现数据共享
·Actions:异步操作;Mutations:同步操作;state:存储公用数据
·组件调用Dispatch方法来调用Action进行异步操作,组件或Actions调用Commit方法来调用Mutations进行同步操作,从而改变state里面的值
如何使用vuex
1、安装vuex
npm
npm install vuex --save
2、引用vuex
import Vue from 'vue'
import Vuex from 'vuex'
//vuex为插件,vue中使用vuex用vue.use()
Vue.use(Vuex)
3、因为vuex比较复杂,可以单独新建一个js文件
store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
//new Vuex.Store 新建一个仓库
export default new Vuex.Store({
state: {
//公用数据 列如:city: '北京'
timed: '00:00:20',
judge: 0
},
actions: {
// ctx 上下文 可以调用commit这个方法
changeTime (ctx, item) {
// commit:同步操作,写法:this.$store.commit('mutations方法名',值)
//调用mutations里面的方法
ctx.commit('changeTime', item)
}
},
mutations: {
changeTime (state, item) {
console.log(item.timed, item.judge, 'juuu')
//将传入的值赋值给state里的值
state.timed = item.timed
state.judge = item.judge
}
}
})
4、在main.js中引入该文件
import store from './store'
//创建实例时,将store传入
new Vue({
store: store
})
5、在页面上引用
//引用store里的state里的city
<div>{{this.$store.state.timed}}</div>
6、改变公共数据
//在需要改变的页面中写这个方法,通过该方法改变共用的值
handleTime (item) {
// dispatch:含有异步操作,例如向后台提交数据,
//写法: this.$store.dispatch('action方法名',传入的值)
this.$store.dispatch('changeTime', item)
}
7、当没有异步操作时,可直接调用commit方法
handleTime (item) {
//写法: this.$store.commit('mutations方法名',传入的值)
this.$store.commit('changeTime', item)
}