vuex 用法
目录结构如下
--store
--modules
--one.js
--two.js
--three.js
index.js
直接上代码:
// one.js 文件
import http from '$path' // 引入请求方法
const state = {
name: null,
age: null
}
const mutations = {
updateSomting : (state, payload) => {
state.name = payload
}
}
const actions = {
functionName1 ({commit, state}, payload) {
commit(updateSomting, payload)
},
functionName2 ({commit, state}, payload) {
return new Promise((resolve, reject) => {
http.get("$url").then((res) => {
if(res) {
let con = res.content
commit('updateSomting', con)
}
}) .catch (err => {
console.log("错误处理=====")
reject(err)
})
})
}
}
erport {
}
// index.js 文件
import Vue from 'vue'
import Vuex from 'vuex'
import one from './modules.one'
Vue.use(Vuex)
export default new Vuex.Store {
namescaped: true,
state: {
},
modules: {
one
},
mutations: {
updateSomting : (state, payload) => {
state.name = payload
}
},
actions:{
functionName1 ({commit, state}, payload) {
commit(updateSomting, payload)
}
},
}
// 在主入口文件main.js中引入store index.js 文件 eg:
import store from 'store/index'
// 其他组件中使用store 中state以及触发action用法
1)获取全局state 状态
2) 触发store actions
this.$store.dispatch('one/functionName2', payload) // 涉及到异步获取服务端数据
3)更新 store 下 mutations

浙公网安备 33010602011771号