VUEX 基础语法
VUEX可以为项目添加一个数据仓库,当不同的组件需要获取或者设置数据时,都从这个仓库中获取。
这里直接记录的是VUEX模块式开发的语法。
目录结构:store文件保存VUEX的处理逻辑,这里设置了两个模块化仓库search和typenav,store下的index.js对外导出,并且内部会注册模块化仓库。
VUEX的注册
首先需要在js(本例中是store/index.js)中引入Vue和Vuex,并调用Vue.use(Vuex)
import Vue from 'vue'
import Vuex from 'vuex'Vue.use(Vuex);
该js应该对外暴露一个Vuex的实例,该实例通过Vuex.Store创建:
export default new Vuex.Store({...
})
在项目的入口js,一般是main.js中,引入这个index.js,并在Vue中注册:
...
import store from '@/store'
...new Vue({render: h => h(App),...store,...
}).$mount('#app')
注册后,在组件中,可以使用this.$store访问仓库。
然后介绍VUEX每个仓库中都需要具有的一些对象:
state
state对象保存仓库的数据。
const state={list : [],
};
mutations
mutations对象是唯一可以修改state数据的对象。
mutations对象中保存一些方法,每个方法的参数为(state, 其他参数)
const state={list : [],
};const mutations = {async getList(state){let tmpList = await reqcategoryList();state.list = tmpList.data;}
};
mutations对象中定义的方法,可以通过$store.commit(方法名)来触发。
this.$store.commit('TypeNav/getList');
actions
actions可以用来触发commit。
actions接收接受一个与 store 实例具有相同方法和属性的 context 对象。
const state={list : [],
};const mutations = {async getList(state){let tmpList = await reqcategoryList();state.list = tmpList.data;},
};const action = {getListAction(context){context.commit('getList')},
}
actions方法通过this.$store.dispatch(方法名)来触发。
小仓库里的代码框架
TypeNav/index.js中的代码如下:
需要注意,因为项目中有多个小仓库,为了在commit时指定是哪个仓库中的mutations方法,在对外暴露的对象中,需要加一句namespaced:true。
import { reqcategoryList } from '@/api'
const state={list : [],
};const mutations = {async getList(state){let tmpList = await reqcategoryList();state.list = tmpList.data;}
};const action = {}export default{namespaced: true,state,mutations,action,
}
search/index.js代码框架是一模一样的:
const state={...
};const mutations = {...
};const action = {...
}export default{namespaced: true,state,mutations,action,
}
在store/index.js中通过import引入两个小仓库,再在Vuex.Store()中通过modules方法进行模块化:
import Vue from 'vue'
import Vuex from 'vuex'import search from './search'
import TypeNav from './TypeNav';Vue.use(Vuex);export default new Vuex.Store({modules:{search,TypeNav,},
})
组件中调用仓库
调用commit方法
commit方法使用this.$store.commit(仓库名/commit方法名)调用:
this.$store.commit('TypeNav/getList');
读取state中的数据:
state中的数据使用this.$store.state.仓库名.数据名获取
this.$store.state.TypeNav.list;