vuex 修改store中的数据 3

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

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: {}
})

Vuex.Store,state是用来存储数据的对象,mutations是用来修改state数据的方法。state数据可以被组件通过this.$store.state来访问,而mutations的方法可以被组件通过this.$store.commit来调用。下面是state和mutations的详细介绍: 1. state state是Vuex.Store用来存储数据的对象,它包含了应用程序所有需要管理的状态。state数据可以被组件通过this.$store.state来访问。例如,你可以在Vuex.Store定义一个名为`count`的state,代码如下: ```javascript const store = new Vuex.Store({ state: { count: 0 } }) ``` 在这个例子,我们在state定义了一个名为`count`的变量,初始值为0。组件可以通过`this.$store.state.count`来访问这个变量。 2. mutations mutations是Vuex.Store用来修改state数据的方法,它们必须是同步函数。mutations的方法可以被组件通过`this.$store.commit`来调用。例如,你可以在Vuex.Store定义一个名为`increment`的mutation,代码如下: ```javascript const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count++ } } }) ``` 在这个例子,我们定义了一个名为`increment`的mutation,它将state的`count`变量加1。组件可以通过`this.$store.commit('increment')`来调用这个mutation。 mutations的方法也可以接收额外的参数,例如: ```javascript const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment(state, amount) { state.count += amount } } }) ``` 在这个例子,我们定义了一个名为`increment`的mutation,它将state的`count`变量加上额外的`amount`参数。组件可以通过`this.$store.commit('increment', 10)`来调用这个mutation,将`amount`参数设置为10。 mutations的方法还可以被异步调用,但是异步操作不能直接修改state数据。如果需要在异步操作修改state数据,可以使用actions来实现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值