Vue VueX基础

创建 store  注册VueX

// 引入Vue实例
import Vue from "vue";
// 引入VueX
import Vuex from "vuex";
// 将VueX use() 到Vue上 在这里在Vue原型链上添加了$store
Vue.use(Vuex);

注册VueX.Store({ })  对象 里面有五个参数

  1. state 存放数据
  2. mutations 存放同步方法
  3. actions 存放异步方法
  4. getters 存放计算属性
  5. Module 对store实行模块化

state 的两种传值方式

state: {
  count: 100
},
// 在标签内直接引用
{{ $store.state.count }}
// 第一步引入vuex 解构出mapState
import { mapState } from 'vuex'
// 在计算属性中
computed: {
  ...mapState(['count']),//函数是对象的结构, 所以放到计算属性里面
},

 getters 计算属性的两种方法       对数据进行操作后一定要return 出去

  getters: {
    getadd(state) {
      return (state.count += 1001);
    },
    getsub(state) {
      return (state.count -= 10900);
    },
  },
// 第一种调用方法是用的
{{ $store.getters.getadd }}
// 第二种引入mapGetters
computed: {
    ...mapGetters(['getsub']) 
}

mutations 同步方法    的两种传值方式      

//在上面直接定义方法 通过commit方法来调用 第一个参数方法名  第二个参数值
btn() {
    this.$store.commit('add', 4)
},
// 第二种引入mapMutations  进行解构
import { mapMutations } from 'vuex'
// 在methods里面先导入方法 在this.方法 调用
methods: {
        ...mapMutations(['sub']), //引过来的是方法  需要在调用一下
        addSub() {
            this.sub(10)
        }
    }

actions: 异步方法 的两种传值方式          里面方法的参数是store可以直接  .方法名

//构造方法  模拟异步操作
actions: {
    timeAdd(store) {
      setTimeout(() => {
        store.commit("add", 10);
      }, 1000);
    },
    timeSub(store) {
      setTimeout(() => {
        store.commit("sub", 10);
      }, 1000);
    },
  },
// 第一种调用方式 也是在methods里面
// 调用 actions 使用dispatch
methods: {
    tiembtn() {
        this.$store.dispatch('timeAdd')
    }
}
// 第二种 导出 mapActios
import { mapActions } from 'vuex'
// 和mutations一样 导入方法 调用this.方法名
methods: {
    ...mapActions(['timeSub']),
    timeBtnSub() {
        this.timeSub()
    }
}

2023/4.25补充 

mutations里面第一个参数实例时status ,第二个是页面传递过来的值

actions里面第一个参数实例时store实例,第二个是传递到status里面的值

import Vue from 'vue';
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
	state:{
		conut:0
	},
	mutations:{
		add(status,value){
			status.conut+=value
		}
	},
	actions:{
		asyncAdd(store,value){
			store.commit('add',value)
		}
	}
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值