vue3+vuex 的 mutations 的 使用

<template>
  <div class="app">
    姓名:{{$store.state.nameVuex}}
    <button @click="btn">基本方法 : 修改名字</button> <br/>
    <button @click="btn1">传递值 : 修改名字</button>
    
    <h3>方法(映射状态) : 只适合vue3</h3>
    <button @click="changgeName">基本方法 : 修改名字</button> <br/>
    <button @click="changgeName1('传递值')">传递值 : 修改名字</button>

  </div>
</template>


<script setup>

import { mapMutations } from 'vuex';

import { useStore } from 'vuex';
const store = useStore()

// 1.手动的映射和绑定
const mutations = mapMutations(["changgeName", "changgeName1"])
const newMutations = {}
Object.keys(mutations).forEach(key => {
  newMutations[key] = mutations[key].bind({ $store: store })
})
const { changgeName, changgeName1 } = newMutations

</script>
import { createStore } from 'vuex'

export default createStore({
  state: {
    nameVuex:'yjx',
    levelVuex:100,
    avtarURLVuex:'http',
    counterVuex:100,
    friends:[
      {id:111,name:'why0',age:20},
      {id:112,name:'why1',age:30},
      {id:113,name:'why2',age:26}
    ]
  },
  // 计算属性 参数1:state  参数2:getters
  getters: {
    // 基本使用
    counterGetter(state){
      return state.counterVuex * 2
    },

    usersAgesGetter(state){
      return state.friends.reduce((pre,item)=>{
        return pre+item.age
      },0)
    },

    // 使用其他的getters : 采用参数2
    message(state,getters){
      return `名字:${ state.nameVuex } , 等级 :${ state.levelVuex} , 朋友年龄总和 ${getters.usersAgesGetter}`
    },

    // 获取某id的朋友
    firendId(state){  
      return function(id){
        return state.friends.find(item=>item.id === id)
      }
    }
  },

  // mutations : 想修改state的值必须通过mutations来修改
  // mutations 参数1:state的   参数2.传递过来的数据
  mutations: {
    changgeName(state){
      state.nameVuex = '吴宇腾'
    },
    changgeName1(state,payload){
      state.nameVuex = payload
    }
  },
  actions: {

  },
  modules: {

  }
})

 

posted @ 2022-08-29 18:14  杨建鑫  阅读(749)  评论(0编辑  收藏  举报