vuex有哪几种属性和使用

Vuex是在大型项目中,组件之间传值不易,用vuex集中管理状态
场景有:单页应用中,组件之间的状态

一、属性介绍

分别是 State、 Getter、Mutation 、Action、 Module
state => 基本数据(数据源存放地)(this.$store.state直接用)
getters => 从基本数据派生出来的数据
mutations => 提交更改数据的方法,同步!
actions => 像一个装饰器,包裹mutations,使之可以异步。
(放异步数据请求,如果不是异步请求,组件可以直接调用commit触发mutations的方法)
modules => 模块化Vuex

但是组件不能直接修改state中的数据,如果要修改需通过this.$store.dispath触发actions中定义的方法
在actions中,通过ctx.commit()触发mutations中定义的方法
在mutations中可以修改state值

一、获取值

main.js

  store.state..msg

index.vue

this.$store.state.msg
  <p>
      vuex的msg数据是:
      <span>{{ this.$store.state.msg }}</span>
  </p>

二、改值

store.js

 state: {
    num: 88,
  },
  actions: {
    changeactnum(ctx, data) {
      ctx.commit('changemutnum', data)
    }
  },
  mutations: {
    changemutnum(state, data) {
      state.num = data
    }
  },

index.vue

//有异步操作,先调用actions中的cxt.commit()去调用mutations中的方法
 changenum() {
      let num = 100
      this.$store.dispatch('changeactnum', num)
    }// 如果没有异步操作,也可以直接用commit调用 mutations中的方法
  changenum() {
      let num = 100
      this.$store.commit('changemutnum', num)
      }

三、辅助函数 mapMutations, mapActions

store.js

 state: {
    num: 88,
  },
  actions: {
    changeactnum(ctx, data) {
      ctx.commit('changemutnum', data)
    }
  },
  mutations: {
    changemutnum(state, data) {
      state.num = data
    }
  },

index.vue

import {mapMutations, mapActions } from 'vuex'
 // 辅助函数mapActions
      ...mapActions(['changeactnum']),
      changenum() {
        let num = 100
        this.changeactnum(num)
       }
 // 辅助函数mapMutations
       ...mapMutations(['changemutnum']),
       changenum() {
          let num = 100
          this.changemutnum(num)
        },

四、辅助函数 mapState

store.js

 state: {
     city: '郑州'
  }

index.vue

 <p>{{ city }}</p>
 
import { mapState} from 'vuex'
 computed: {
    //辅助函数mapState   mapGetters
     ...mapState(['city']),
    },

五、辅助函数 mapGetters

store.js

 state: {
    students: [
      { id: '1', name: 'Amy', age: 20 },
      { id: '3', name: 'Alice', age: 34 },
      { id: '4', name: 'Green', age: 210 },
      { id: '5', name: 'Jack', age: 40 },
      { id: '6', name: 'Grace', age: 10 }
    ],
  }getters: {
    selectedStudents(state) {
      return state.students.filter(item => item.age > 30)
    }
  },

index.vue

 <ul>
     <li v-for="(item, index) in selectedStudents" :key="item.id">
          {{ item.name }}--{{ item.age }}---{{ index }}
     </li>
 </ul>
 
import { mapGetters} from 'vuex'
 computed: {
   //辅助函数mapGetters
     ...mapGetters(['selectedStudents']),
    },
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值