为方便自身查阅,直接上代码
官网地址:Vuex 是什么? | Vuex (vuejs.org)
npm下载地址:
npm install vuex@next --save
根目录新建store->index.js文件
// index.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
count: '我很帅'
},
mutations: {
increment(state) {
state.count++;
},
decrement(state) {
state.count--;
}
},
actions: {
increment(context) {
context.commit('increment');
},
decrement(context) {
context.commit('decrement');
}
},
getters: {
getCount: state => state.count
}
});
main.js引入
//main.js
import store from './store/index.js'
Vue.prototype.$store = store
——————————————————以上引入完成
——————————————————以下使用方法
(以下栗子以index.js文件数据为例)
一、state (管理组件数据,管理的数据是响应式的)
组件调用:this.$store.state.属性名,辅助函数:mapState ,getters调用:this.$store.getters.属性名 ,getters辅助函数也可调用——方法在四
注:辅助函数使用方式
index.vue
import {
mapState,
mapGetters,
mapActions,
mapMutations
} from 'vuex'
computed: {
...mapState(['count'])
},
二、mutations (更新数据,state中的数据只能使用mutations去改变数据—同步)
组件调用:this.$store.commit ,辅助函数:mapMutations(对象形式可传参)
注:辅助函数使用方式
// index.vue页面
一、对象形式映射 (可传参)
methods: {
// 事件同级
// param 为自定义方法名(传参用)
// activeNumber 为vuex中方法名
...mapMutations({
param: 'activeNumber'
}),
// 触发纽扣
dianji() {
// vuex 辅助函数调用+传参
this.param(15)
},
}
二、数组形式映射 (不可传参)
methods: {
...mapMutations([
'activeNumber',
])
}
三、action (提交的是 mutation,而不是直接变更状态—异步)
组件调用:this.$store.dispatch ,辅助函数:mapActions(对象形式可传参)
//index.vue
methods: {
handleQuery () {
// 触发action(必须调用dispatch方法)
this.$store.dispatch('activeNumber', 111)
// 以载荷形式分发
this.$store.dispatch('activeNumber', {
amount: 10
})
// 以对象形式分发
this.$store.dispatch({
type: 'activeNumber',
amount: 10
})
}
// 构造函数调用方法和 mapMutations 一致
// 事件同级
...mapActions([
'activeNumber', // 将 `this.increment()` 映射为`this.$store.dispatch('increment')`
]),
...mapActions({
param: 'activeNumber'
}),
dianji() {
// action 辅助函数
this.param(15)
},
}
可以通过action调用处理接口数据后通过commit 传给mutations
// vuex中代码
actions: {
// 第一个参数通常为context可以拿到vuex中的dispatch、commit、state、getters...等多项
GetRoute({ commit, state }, menuKey) {
return new Promise((resolve, reject) => {
if (!state.menus) {
indexMenusApi().then(resp => {
commit('SET_MENUS', resp.data.data)
})
}
const route = filterRoute(state.menus, menuKey)
resolve(route)
})
},
}
mutations: {
SET_MENUS: (state, menus) => {
state.menus = menus
},
}
四、getters (可以认为是 store 的计算属性)
组件调用:this.$store.getters.属性名 ,辅助函数:mapGetters
// vuex中
state: {
menus:'我很帅',
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
}
getters: {
// 可以封装一些共享函数
doneTodos (state) {
return state.todos.filter(todo => todo.done)
}
// 也可以在组件中通过mapGetters辅助函数直接使用
globalMenus: state => state.menus,
}
// 页面中
computed: {
... mapGetters([
// 可以直接使用
'globalMenus'
])
}
以上完————编写博客时意外点了撤回 差点功夫白费,幸好自带历史回退