VueX 的使用

引入Vuex

npm install --save vuex@3 

使用Vuex

src下创建store文件夹,index.js文件

// 1
import Vue from 'vue'
// 2
import Vuex from 'vuex'
// 3
Vue.use(Vuex)
// 4
export default new Vuex.Store({
​ state:{},
​ mutations:{},
​ actions:{},
​ setters:{}
})

main.js中

// 1
import store from './store'
// 2
new Vue({
​ el:'app',
​ store,
})

组件中访问state中数据

  1. this.$store.state.name

  2. import {mapState} from 'vuex'
    computed:{
    ​ ...mapState(['name'])
    }

修改state中数据

store/index.js

mutations:{
​ add(state){
​     操作state.name
​ }
}

组件:

this.$store.commit('add')

mutations传参

在mutations方法中第二个参数接收传递的参数

store/index.js

mutations:{
​ add(state, 参数){
    //
​ }
}

组件:

commit()中第二个参数作为传递的参数

this.$store.commit('add' , 参数)

第二种触发mutations的方法

按需导入mapMutations函数

import { mapMutations } from 'vuex'

将需要的mutations函数映射为当前组件的methods

methods:{
​ ...mapMutations(['add','sub'],
​ btnHandler(){
​     this.add(参数)
​ }
}

actions

actions里用来执行异步操作

actions:{
​ asyncAdd(context){
​  setTimeout(function(){
​   context.commit('add')
​  },1000)
​ }
}

组件中使用dispath分发actions

this.$store.dispath('asyncAdd')

快速记忆

this.$store.state.

import { mapState, mapMutations, mapActions } from 'vuex'

...mapState([''])

...mapMustations([''])

...mapActions([''])

this.$store.commit()

this.$store.dispath()

state.name

context.commit()

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值