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

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状态持久化(缓存到本地)

store/index.hs的export default中添加配置:

// 引入vuex-persistedstate,将vuex的数据持久化到本地 export default new Vuex.Store({ state, mutations, getters, actions, plugins: [ createPersistedState({ storage: { getItem: key => wx.getStorageSync(key), setItem: (key, value) => wx.setStorageSync(key, value), removeItem: key => {} } }) ] })

Tips

遇到安装依赖后,运行项目,但dist下没有app.js等入口文件的,将package.json里的mpvue-loader的版本前的^去掉,删除依赖,重新安装即可

在onLoad周期内执行获取数据等初始化操作,因为mpvue的created钩子执行要早得多(小程序运行时)

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/e3c7041e555f77bfdb55ddf865468342.html