vue2+vuex 的 mutations 的 使用
<template> <div class="app"> 姓名:{{$store.state.nameVuex}} <button @click="btn">基本方法 : 修改名字</button> <br/> <button @click="btn1">传递值 : 修改名字</button> <h3>方法(映射状态) : 只适合vue2</h3> <button @click="changgeName">基本方法 : 修改名字</button> <br/> <button @click="changgeName1('传递值')">传递值 : 修改名字</button> </div> </template> <script> import { mapMutations } from 'vuex'; export default { methods:{ // 基本方法 btn(){ this.$store.commit('changgeName') }, // 传参 - 也可以传递对象 btn1(){ this.$store.commit('changgeName1','传递值') }, ...mapMutations(['changgeName','changgeName1']) } } </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: {
}
})
本文来自博客园,作者:杨建鑫,转载请注明原文链接:https://www.cnblogs.com/qd-lbxx/p/16636872.html

浙公网安备 33010602011771号