刚开始接触uniApp看了一下vuex的使用方法,总结一下在项目中个人认为常用的架构,很实用,做一个新手学习笔记!!!
文件目录结构图
创建store目录
使用HBuilderx创建项目,在项目内创建store目录,在目录内创建index.js文件,如下
namespaced : true 调用时候 需要加上所属的模块名可以参数第二种调用方式
import Vue from 'vue'
import Vuex from 'vuex'
import star_sky from './modules/public/star_sky.js'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
//放置全局变量
},
modules: {
//数据模块化
star_sky: {
namespaced: true,
...star_sky
}
}
})
export default store
在store内创建mutations_type.js
mutations_type.js 是方便异步方法actions 调用同步方法mutations 去更新数据时调用,不容易出错而且模块化后方法是通过所属模块名称去调用
//页面请求实体数据
export const REQUEST_DATA = 'REQUEST_DATA'
store目录内创建modules
modules 是各个模块对应的文件
modules 内创建公共模块文件夹
public内都是多个UI共享数据,创建star_sky.js 文件
创建star_sky.js
import { REQUEST_DATA } from '../../mutations_type.js'
const state = {
ceshidata: []
}
const mutations = {
[REQUEST_DATA] (state, data) {
state.ceshidata = data
}
}
const actions = {
async getDevicesData ({ commit },data) {
console.log("UI 界面调用 异步actions 内方法")
// 异步操作 ---请求数据
//同步操作 更新 ceshidata 数据
commit(REQUEST_DATA, data)
}
}
export default {
state,
mutations,
actions
}
在main.js中配置store
import store from 'store/index.js'
Vue.prototype.$store = store
const app = new Vue({
...App,
store
})
调用模块
方式一
- mapState 是引用模块内state内的数据
- mapActions 是引用模块内actions 内的方法 (异步)
- mapGetters 是引用模块内 getters 内的方法 (获取数据)
- mapMutations 是引用模块内 mutations 的方法 (同步修改state)
- 在vue script 内引入vuex
import { mapState, mapActions } from 'vuex'
- mapState
namespace:true 需要加上模块名称 ,在export default 内 创建 computed 导出 模块 mapState 方法
computed: {
...mapState('star_sky', ['ceshidata'])
}
- mapActions
namespace:true 需要加上模块名称 ,在export default 内 创建 methods导出 模块 mapActions方法
methods: {
...mapActions('star_sky', ['getDevicesData'])
}
- mapGetters
namespace:true 需要加上模块名称 ,在export default 内 创建 computed 导出 模块 mapGetters 方法
computed: {
...mapGetters('star_sky', ['方法名'])
}
- mapMutations
namespace:true 需要加上模块名称 ,在export default 内 创建 methods导出 模块 mapMutations方法
methods: {
...mapMutations('star_sky', [REQUEST_DATA])
}
方式二
这都是建立在namespace:true的前提下,如果namespace:false 则去掉模块名
- mapState 是引用模块内state内的数据
- mapActions 是引用模块内actions 内的方法 (异步)
- mapGetters 是引用模块内 getters 内的方法 (获取数据)
- mapMutations 是引用模块内 mutations 的方法 (同步修改state)
- mapState
结构:this.$store.state.模块名.模块属性
this.$store.star_sky.ceshidata
- mapActions
结构:this.$store.dispatch('模块名 / 模块中的actions',值)
this.$store.dispatch('star_sky/getDevicesData',[{'ceshikey': '第二种方法'}])
- mapGetters
结构:this.$store.getters.模块名.模块属性
//this.$store.getters.star_sky.doneTodosCount
this.$store.getters.模块名.模块属性
- mapMutations
结构:this.$store.commit('模块名 / 模块中的mutations',值)
this.$store.commit('star_sky/模块中的mutations',[{'ceshikey': '第二种方法'}])