亲测可用,若有疑问请私信
注解:vuex是一个很简单、很方便的技术,入门很简单,这里给大家详细介绍下vuex的进阶使用。
一、vuex模块化modules
1、项目根目录新建一个sotre文件夹,在store文件夹内,新建两个文件(一个文件,一个文件夹),一个index.js文件,一个modules文件夹。
目录结构:
store
index.js --文件
modules --文件夹
2、store->index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import Vue from 'vue' import Vuex from 'vuex' import modules from './modules' Vue.use(Vuex) export default new Vuex.Store({ state: { }, mutations: { }, actions: { }, modules:modules. //注意哦,后一个modules文件夹中有index.js文件,所以可以直接写文件夹名,前端中文件夹中有index.js 可以只写文件夹名(默认引入文件夹中的index.js) }) |
3、store->modules
目录结构
store
index.js
modules
index.js //将所有模块引入一个js文件,统一导出,store->index.js中就只需要引入modules,类似modules->index.js
cart.js //购物车模块
login.js //登陆模块
4、具体模块写法,cart.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | //cart.js const state={ cart: "one-sotre" } const actions={ cart({commit},data){ commit( "cart" ,data) } }; const mutations={ cart(state,data){ state.cart=data; } } export default { state, actions, mutations } |
5、将store->modules->[cart.js,login.js]导入store->modules->index.js中,统一处理导出
1 2 3 4 5 6 7 | //store->modules->index.js import login from './login' ; import cart from './cart' ; export default { login, //键值相同时,login:login==login cart } |
6、在store->index.js中使用导出[login,cart]模块
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import Vue from 'vue' import Vuex from 'vuex' import modules from './modules' . //简写,引入modules/index.js Vue.use(Vuex) export default new Vuex.Store({ state: { }, mutations: { }, actions: { }, modules:modules }) |
在main.js中引入即可。
7、vue components组件中使用
//使用vuex中的函数mapState、mapAction,需要注意mapState、mapGetter这两个需要数据实时更新的书写在computed计算属性中,mapAction等方法写在methods方法中。
1 2 3 4 5 6 7 8 9 10 11 12 13 | //.vue,这里只讲两个方法,mapState和mapAction,mapState和[mapGetters,mapMutions,mapActions]写法可以简单分为两种,所以介绍两种写法. <script> import { mapState, mapActions } from 'vuex' export default { mounted(){ this .login( "true" ); //调用mapActions['login']; console.log( this .login) //调用..mapState({login:state=>state.login.login}) }, methods:{<br> // 在uniapp中写法,可以直接映射模块中的login ...mapActions([ 'login' ]). //这里引入的是store->modules->login.js中的vuex Actions方法,...mapActions['login']==this.$store.dispatch("login"),mapMutions,mapActions写在methods中.<br> //在vue中写法,需要加上模块名称,如modules中的login中的login方法,写法如下<br> ...mapActions({'login':'login/login'}). //指store.dispatch('login/login'); |
1 2 3 4 5 6 | }, computed{ ...mapState({login:state=>state.login.login}) //这里引入的是store->modules->login.js中的state数据,...mapState({login:state=>state.login.login})==this.state.login.login;mapState,mapGetters写在computed中,跟computed自身属性有关. } } </script> |
//这个文档聚集了modules 模块化写法,vuex基础用法,mapState、mapGetters辅助函数的使用。