vuex 方便的实现组件之间数据共享(数据是响应式的,自动刷新)
组件的数据 =》 store =》 其他任意组件
相当于:
组件内的data为私有数据
vuex中的data是全局数据
(一)安装
npm install vuex --save
(二)main.js同级目录下的store.js文件内容
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {},
mutations: {},
actions: {},
getters: {}
})
export default store
(三)将store 对象挂载到vue实例中(main.js)
import store from './store'
new Vue({
router,
store,
render: h => h(App),
}).$mount('#app')
(四)组件中调用全局数据
const store = new Vuex.Store({
// state 中存放的就是全局共享的数据
state: {
// 全局数据,默认为0
count: 0
},
mutations: {},
actions: {}
})
this.$store.state.count
访问state中数据的第一种方式:
在组件中template中this省略:
{{ $store.state.count }}
访问state中数据的第二种方式:
1,导入
import { mapState } from 'vuex'
2,定义计算属性(映射为计算属性)
computed: {
...mapState(['count'])
}
3,页面中调用
{{ count }}
(五)mutations修改state中的数据
(不要直接this.$store.state.count++ 类似这种操作)
const store = new Vuex.Store({
state: {},
mutations: {
// 不要在 mutations 函数中使用异步操作,例如:setTimeout
// state 是指上面的state对象
add(state){
state.count++
}
},
actions: {}
})
组件中调用mutations里面的函数
第一种方式:
this.$store.commit('add')
// add 是函数名
第二种方式:
import { mapMutations } from 'vuex'
methods: {
...mapMutations(['add', 'sub']),
addCount(){
this.add()
}
}
(六)触发mutations函数时传参数
const store = new Vuex.Store({
state: {},
mutations: {
// state 是指上面的state对象
add(state, step){
state.count += step
}
},
actions: {}
})
组件中调用mutations里面的函数
第一种方式:
this.$store.commit('add', 3)
第二种方式:
import { mapMutations } from 'vuex'
methods: {
...mapMutations(['add', 'sub']),
addCount(){
this.add(2)
}
}
也可以直接调用
<button @click="add(2)">
(七)actions 用于处理异步任务
const store = new Vuex.Store({
state: {},
mutations: {},
actions: {
addAsync(context){
setTimeout(() => {
// 在actions中,不能直接修改 state 的数据
// 必须通过 context.commit() 触发某个 mutations 才行
context.commit('add')
}, 1000)
},
// 传参
addAsync(context, step){}
}
})
触发actions 的第一种方式:
this.$store.dispath('addAsync')
传参
this.$store.dispath(‘addAsync’, 5)
触发actions 的第二种方式:
import { mapActions } from 'vuex'
methods: {
...mapActions(['addAsync']),
}
直接调用
<button @click="addAsync">
传参
<button @click=“addAsync(3)”>
(八)Getter 用于对 state 中的数据进行加工处理形成新的数据
state 中数据发生变化,Getter 的数据也会发生变化, 不会修改 state的数据
const store = new Vuex.Store({
state: {},
mutations: {},
actions: {},
getters: {
showNum(state){
return '当前数量' + state.count
}
}
})
调用的第一种方式:this.$store.getters.showNum
{{ $store.getters.showNum }}
调用的第二种方式:
import { mapGetters } from 'vuex'
computed: {
...mapGetters(['showNum'])
}
{{ showNum }}