Vuex的核心内容(State,Getter,Mutation,Action)

目录

State(读取状态)

Getter(对Vuex中的数据进行过滤)

 Mutation(更改vuex中的状态)

 Action(类似于Mutations,不同的是Action是异步)

State(用于存储状态)

1.读取状态(在store/index.js中存储count的值)

 state: {

     count:4

  },

 2.在组件中读取出来(两种方法)

直接读取

<p>{{ $store.state.count }}</p>

 使用mapState读取

<template>

  <div class="admin">

   <p>{{ count }}</p>

  </div>

</template>

<script>

import { mapState } from "vuex";

export default{

  name: 'Admin',

  computed:{

    ...mapState(['count'])

  }

}

</script>

Getter(对Vuex中的数据进行过滤)

1.设置过滤条件(在store/index.js中)

 

  state: {

    count: 0

  },

getters: {

    getcount(state) {

      return state.count > 0 ? state.count : "数据错误"

    }

  },

2.在组件中读取(两种方法)

直接读取

 <p>{{ $store.getters.getcount }}</p>

 使用mapGetters读取

<template>

  <div class="plant">

    <p>{{ getcount }}</p>    //直接读取

  </div>

</template>

<script>

import { mapGetters } from 'vuex';    引入mapGetters

export default{

  name: 'Plant',

  computed:{

    ...mapGetters(['getcount'])

  }

}

</script>

3.展示

 Mutation(更改vuex中的状态)

1.改变状态的函数

 mutations: {

    addcount(state,num){

      state.count+=num

    }

  },

2.在组件中设置点击事件触发函数(两种触发方法)

直接触发

this.$store.commit("addcount",10)

简洁触发

 Action(类似于Mutations,不同的是Action可以是异步)

 1.改变状态的异步函数

  actions: {

    asyncaddcount({commit}){

      axios.get("http://iwenwiki.com/api/generator/list.php").then(res=>{

        commit("addcount",res.data[0])

      })

    }

  },

 2.在组件里设置点击事件触发函数

3.调用函数方法

this.$store.dispatch("asyncaddcount")

 简洁调用

 import { mapGetters,mapActions } from 'vuex';

 ...mapActions(['asyncaddcount']),

  this.asyncaddcount()

 本文为本人自身学习记录

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值