mpvue+vuex搭建小程序详细教程(完整步骤)

2020-06-13 10:30:08易采站长站整理

2、main.js中引入store, 并绑定到Vue构造函数的原型上,这样在每个vue的组件都可以通过this.$store访问store对象。


import store from './store/index'
Vue.prototype.$store=store;

3、定义初始变量store/state.js


const state={
openId: '',
}
export default state

4、mutation类型

方便检测错误和书写,一般写方法


export const SET_OPEN_ID = 'SET_OPEN_ID'

5、store/mutations.js

写处理方法


import * as types from './mutation-types'
const matations={
/**
* state:当前状态树
* v: 提交matations时传的参数
*/
[types.SET_OPEN_ID] (state, v) {
state.openId = v;
},

}

export default matations

6、store/index.js

汇总配置


import Vue from 'vue';
import Vuex from 'vuex';
import state from './state'
import mutations from './mutations'

Vue.use(Vuex);

export default new Vuex.Store({
state,
mutations,
})

使用vuex

ps:没有用到复杂计算,因此没有引入getters.js和actions.js

栗子:App.vue


<script>
import { login } from '@/http/api'
import { mapState, mapMutations } from 'vuex'
import { SET_OPEN_ID } from './store/mutation-types'
const App = getApp();
export default {
data: {
globalData: {}
},
computed: {
...mapState([
'openId'
])
},
methods: {
...mapMutations({
setOpenId: 'SET_OPEN_ID'
}),
// 使用了async+await的语法,用同步的方式写异步脚本
async login(code) {
let _this = this;
try {
const resData = await login({ code: code });
if (resData.returnCode == 200) {
_this.setOpenId(resData.data.accountId)
}
} catch (err) {
console.error(err);
}

},
// 拆分wx.login,结构更清晰
_login() {
let _this = this;
wx.login({
success(res) {
if (res.code) {
console.log('wx.login成功,code:', res.code);
let code = res.code;
_this.login(code)
} else {
_this.$tips.toast('微信登录失败')
}
}
});
}
},
onLaunch() {
this._login()
}
}
</script>

使用vuex-persistedstate,使vuex状态持久化(缓存到本地)