vuex使用:
在components文件夹同级下新建一个store文件夹.
将store文件夹在main.js中引入,如: import store from './store' 然后在下面vue上挂载上.
store/
state.js
index.js
mutations
mutation-types.js
actions.js
getters.js
这几个js文件主要是干什么的,下面一一介绍:
index.js/ 它主要是引入各个js文件的.如:
import Vue from "vue"
import Vuex from "vuex"
import * as getters from "./getters"
import state from "./state"
import mutations from "./mutations"
Vue.use(Vuex)
export default new Vuex.Store({ getters,state,mutations })
state.js/ 它主要是定义对象,变量的,数组等.如:
const state={
singer: {},
music: {}
}
mutations.js/ 它主要是修改值,获取想要的值然后给state里面定义的赋值.如:
import * as from "./mutation-types"
const mutations = {
[types.SET_SINGER] (state, singer){
state.singer = singer
},
[types.SET_MUSIC] (state, music){
state.music = music
}
}
mutation-types.js/ 它主要是定义名称,避免名称过长,一大串.如:
export const SET_SINGER = 'SET_SINGER'
export const SET_MUSIC = 'SET_MUSIC'
getters.js/ 它主要是返回值.如:
export const singer = state =>{
return state.singer
}
export const music = state =>{
return state.music
}
export const currentSong = state ={
return state.playList[state.currentIndex] || {}
}
使用 例如:
import {mapGetters,mapMutations,mapActions} from 'vuex'
const store = new Vuex.Store({
// 存放数据(状态)
state: {
b: 1
},
// 获取数据,配合computed使用
getters: {
getB(state,getters) {
return state.b
}
},
// 修改数据,不能进行异步操作
mutations: {
setB(state,payload) {
state.b = payload
}
},
// 能进行异步操作
actions: {
setB({commit},payload) {
commit('setB',payload)
}
},
modules: {
cart:{
},
user: {
}
}
<template>
<div class="a">
{{getB}}
<button @click='changeB'>修改b</button>
</div>
</template>
export default {
computed: {
...mapGetters([
"getB"
])
},
methods: {
// 只适合同步操作
...mapMutations([
'setB'
]),
// 能进行异步操作
...mapActions([
'setB'
]),
chanegeB() {
this.setB(12)
}
}
}
})