vuex的使用

在这里插入图片描述

vuex的五个属性

1.state – 存放状态
2.getters – state的计算属性
3.mutations – 更改状态的逻辑,同步操作
4.actions – 提交mutation,异步操作
5.mudules – 将store模块化

使用

const store = new Vuex.Store({ state: { info: {"name":"我是vuex","id":1,"Name":"王二麻子"} } }) 

1、在组件中可以使用来获取vuex中公共的state的值 

this.$store.state.info.Name;//"王二麻子"

也可以使用以下来取值 

import { mapState, mapGetters,mapActions, mapMutations } from "vuex";
 mounted() {
    console.log(mapState);
  },
  computed: {
    ...mapGetters(["getStudentLength"])
  },
  methods:{
  	 ...mapMutations(['sub']),
    ...mapActions(['addA'])
  }

2、在组件中修改vuex中的state的值 

//第一种方法:在组件中
<button type="button"  @click="newName"></button>
methods: {
    newName: function() {
      this.$store.commit('newName', this.newValue)//通过commit调取vuex中的newName事件来修改
    }
  }
  //第二种方法:在组件中
   methods:{
  ...mapMutation(['add','add2'])//这样就能直接创建store中定义在mutations的方法了。
	this.newName(this.newValue)
  }

//在vuex中
 mutations: {
    newName(state,msg) {
      state.info.Name = msg;
    }
  }


3、通过actions来修改vuex中state的值

方法一、
 ...mapActions(['saveDbSource'])//先引入actions里的方法
 this.saveDbSource//使用
 
 方法二、
this.$store.dispatch('saveDbSource', this.DbSource);//通过dispatch调用actions里的saveDbSource

vuex中
actions:{
     saveDbSource(context,num){ //context:上下文对象,这里你可以理解称store本身。
       context.commit('newName',num)//通过调用mutations里是newName方法来改变vuex中的state。
       //这边就是调用mutations的方法,这样才能异步,不要直接调用state中的数据。
       }
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

空城三梦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值