Vue.js之Vuex的使用

目录

 1.state

(1)$store.state.数据名

(2)  利用mapState

2.getters

(1)$store.getters.对应名称

(2)利用mapGetters

3.mutations 

(1)绑定事件

 (2)方法中利用commit调用Vuex中的方法

(3)mutations中的方法如下:

 4.actions

(1)$store调用

(2)mapActions调用


本文主要介绍Vue.js中Vuex的使用,其主要的作用就是实现组件之间的数据通信。

通过Vue脚手架搭建的项目中,src目录存有store文件夹,其中的index.js引入Vuex,存放了组件所需的数据和方法等。如下图所示。

 1.state

state中存储数据

export default new Vuex.Store({
   
    state: {
        count: 10
    }

})

在组件中的访问方式:

(1)$store.state.数据名

 <h1>当前值:{{$store.state.count}}</h1>

(2)  利用mapState

import {mapState} from "vuex";
export default {
   computed:{
       ...mapState(['count'])
   }
}

 而后直接使用即可

<h1>当前值:{{count}}</h1>

2.getters

获取值时进行一些操作

export default new Vuex.Store({
    state: {
        count: 10,
    },
    getters: {
        showMsg(s) {
            return s.count * 100
        }
    }
})

在组件中的访问方式:

(1)$store.getters.对应名称

<div>{{$store.getters.showMsg}}</div>

(2)利用mapGetters

import {mapGetters} from "vuex";
export default {
   computed:{
       ...mapGetters(['showMsg'])
   }
}

 而后直接使用即可:

 <div>{{showMsg}}</div>

3.mutations 

定义方法,操纵state中的数据。注意参数传递

(1)绑定事件

<div><button @click="addOne">点击加1</button></div>
<div><button @click="addN">点击加3</button></div>

 (2)方法中利用commit调用Vuex中的方法

export default {
   methods:
    {
    addOne(){
       this.$store.commit('add');
    },
    addN(){
        this.$store.commit('addN',3)
    }
   }
}

(3)mutations中的方法如下:

mutations: {
        add(s) {
            s.count++
        },
        addN(s, step) {
            s.count += step
        }
    }

即可完成调用

当然,也可以利用mapMutations直接进行调用

 <div><button @click="add">点击加1</button></div>
  <div><button @click="addN(3)">点击加3</button></div>
import {mapMutations} from "vuex";
export default {
   methods:
    {
    ...mapMutations(['add','addN'])
   }
}

 4.actions

进行异步操作,同上述一样,有两种写法。

此时index.js中内容如下:

export default new Vuex.Store({
    state: {
        count: 10,
    },
    getters: {},
    mutations: {
        add(s) {
            s.count++
        },
        addN(s, step) {
            s.count += step
        }
    },
    actions: {
        waitOne(c) {
            setTimeout(() => {
                c.commit('add')
            }, 1000)
        },
        waitN(c, s) {
            setTimeout(() => {
                c.commit('addN', s)
            }, 1000)
        }
    }
})

(1)$store调用

<div><button @click='timeout'>+1</button></div>
export default {
   methods:
    {
    timeout(){
        this.$store.dispatch('waitOne')
    }
   }
}

 

(2)mapActions调用

<div><button @click='waitN(5)'>+N</button></div>
export default {
   methods:
    {
    ...mapActions(['waitN'])
   }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值