Vue项目中Vuex的使用(超级无敌常用版本)

vuex通俗地讲是Vue中的公共的仓库可以存放一些函数及数据,其中主要有四个模块。
1、state:主要是用来存放一些变量数据的地方。
2、mutations:主要用来写一些函数用来改变state里面变量值的。但是只能进行同步操作。
3、actions:主要进行异步操作,将一步操作得到的值传递到mutations中去,一般将请求后台的逻辑写在actions中。
4、getter:有时需要对state中的数据进行过滤和筛选,这时将逻辑写在其中。
下面将以一个简单的例子进行详细说明(加减运算)
版本一:首先先不进行模块化封装,将vuex写在main.js中

//main.js
import Vuex from "vuex"
Vue.use(Vuex);
//下面两个是mutations中函数的名,一般用大写加下划线的方式书写。
const INC_COUNT = 'INC_COUNT';
const DEC_COUNT = 'DEC_COUNT';
//store是Vuex.Store这个构造函数new出来的实例
let store =new Vuex.Store({
	state:{
		total:0,
		users:[
			{name:'yyf',age:18},
			{name:'longdd',age:28},
			{name:'ZSMJ',age:10}
		]
	},
	mutations:{
	//参数state就是前面的state,payload是接受的参数,一般都是用对象形式传递和接收的
		[INC_COUNT](state,payload){
			//这里主要就给state中的变量赋值
			state.total=payload.total
		},
		[DEC_COUNT ](state,payload){
			state.total=payload.total
		},
	},
	actions:{
		//conText中有许多使用的属性和方法,如需查看console.log(conText)就可以查看,常用的也是此处用到commit是向mutations里的函数传递数据;payload 同上。
			incTotal(conText,payload){
				conText.commit(INC_COUNT,payload)
			},
			decTotal(conText,payload){
				conText.commit(DEC_COUNT,payload)
			},
	},
	getter:{
		getUsers(state){
			let myUser=state.users.filter((item)=>{
				return item.age>=18
			})
			return myUser
		}
	}
	
})
//index.vue
<template>
  <div>
    <button @click="decCount()">-</button>
    {{ total }}
    <button @click="incCount()">+</button>

    <ul>
      <li v-for="(item, index) in myUser" :key="index"></li>
    </ul>
  </div>
</template>

<script>
//这里是引入vuex的辅助函数
import { mapActions, mapGetters, mapMutations, mapState } from "vuex";
export default {
  computed: {
      data:{
          return {
              num:0
          }
      },
    //一般vuex中的 state 和 getter 都在computed中引入
    // state一共有两大种引用方法
    // 第一种不用辅助函数:
    total() {
      return this.$store.state.total;
    },
    //第二种使用辅助函数有三种方式(推荐第三种)
    // 1、
    ...mapState(["total"]),
    // 2、
    ...mapState({
      total: "total",
    }),
    // 3、
    ...mapState({
      total: (state) => state.total,
    }),

    // getter也有两大种
    // 不使用辅助函数时
    myUser() {
      return this.$store.getter.count;
    },
    // 使用辅助函数有两种写法(推荐第二种)
    // 1、
    ...mapGetters(["getUsers"]),
    // 2、
    ...mapGetters({
      myUser: "getUser",
    }),
  },
  methods: {
    //Mutations和Actions 一般都写在methods中
    // Mutations没有辅助函数直接触发函数
    decCount() {
      this.$commit("DEC_COUNT",{total:--this.num});
    },
    //如果使用辅助函数有两种方式(推荐第二种)
    // 1、
    ...mapMutations(["INC_COUNT", "DEC_COUNT"]),
    // 2、
    ...mapMutations({
      INC_COUNT: "INC_COUNT",
      DEC_COUNT: "DEC_COUNT",
    }),

    //同理Actions
    //没有辅助函数直接触发函数
    decCount() {
      this.$store.dispatch("decTotal");
    },
    // 有辅助函数(推荐第二种)
    ...mapActions(['incTotal','decTotal']),
    ...mapActions({
        inTotal:'incTotal',
        decTotal:'decTotal'
    }),

    //触发事件,Mutations 和Actions使用辅助函数的方式时
    decCount(){
        this.DEC_COUNT({total:--this.num})//使用Mutations提交,将数据直接传给Mutations
        this.decTotal({total:--this.num})
        //使用actions提交,将数据传到vuex中的actions,过actions中的逻辑传到Mutations中,
        // 一般来说不是异步获取数据不需要使用actions来执行逻辑,此处是为了演示所以使用了actions操作一遍
    }

  },
};
</script>

正常使用时会将vuex模块化
创建store 文件夹,其中包含index.js、modules文件夹。
modules文件夹中包含各个模块 counter.js、user.js、mutation-type.js(mutation-type.js是存放mutations中的函数名一般用于多人开发,单人开发时可以不要。
最后别忘记在main.js中加入store

//index.js
import Vue from 'vue'
import Vuex from 'vuex'
//导入你定义的模块
import counter from '路径'
import user from '路径'

Vue.use(Vuesx)
const store = new Vuex.Store({
    modules: {
        counter,
        user
    }
})
export default store

在模块中要注意命名

//couter.js
export default {
    namespaced: true, //这是为了防止各个模块之间命名冲突
    state: {...},
    mutations: {...},
    actions: {...},
    getters: {...}
}

在index.vue页面中因为模块化所以导致使用的方式发生一些改变

//都需要指出是哪个模块的
computed:{
	...mapState({
		total:state=>state.counter.total
	}),
	//或者在模板里
	//{{$store.state.counter.total}}
	...mapGetter ({
		myUser:'user/getUsers'
	})
}
methods:{
	...mapMutations ({
		INC_COUNT:'counter/INC_COUNT'
	}),
	...mapActions ({
		incTotal:'counter/incTotal'
	})
}
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值