vuex 修改store中的数据 3

本文展示了如何在Vue组件中使用Vuex进行状态管理。通过`myName`计算属性获取Vuex store中的名字,并在点击事件`handleClick`中触发`change` action,经由异步操作更新store状态。同时,深入理解Vuex的mutation和action的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

home.vue

<template>
  <div class="home">
    <h1 @click="handleClick">{{myName}}</h1>
  </div>
</template>
<script>
export default {
  name: 'Home',
  computed:{
    myName(){
      return this.$store.state.name
    }
  },
  methods:{
    handleClick(){
      // 第一步 必须派发一个action change为action
      this.$store.dispatch('change','vuex store 修改后的数据');
    },
  },
  components: {
  }
}
</script>

store / index.js

import {createStore} from 'vuex'

export default createStore({
    state: {
        name: 'dell',
    },
    // mutation 里面 只允许写同步的代码 不允许写异步代码
    mutations: {
        // 第四步,对应mutation被执行
        change(state,str) {
            // 修改数据
            // this.state.name = str;
            state.name = str;
        },
    },
    actions: {
        // 第二步 store感知你触发了一个叫做change的action,执行action
        change(store, str) {
            // 第三步,提交一个 commit 触发一个mutation
            setTimeout(()=>{
                console.log('actions - change')
                this.commit('change', str)
            },2000)
            console.log(store)
            console.log(str)

        }
    },
    modules: {}
})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值