Vuex的数据双向绑定

这篇博客探讨了在Vuex中实现组件与状态管理库数据双向绑定的问题。通过错误示范展示了直接使用会导致的错误,并提出了两种解决方案:一是利用Vue的特性结合 getters 和 mutations;二是利用actions和mutations,分别用于获取和修改值,详细解释了这两种方法的工作原理和实现代码。

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

问题阐述

我们都知道Vueinput 输入框的数据双向绑定是使用 v-model 实现的。但是如果绑定的数据是 Vuex- State 中的数据,直接使用v-model会发生什么呢?

错误示范

store/index.js

state: {
    inputVal: '默认值'
  }

Component

<template>
  <div class="home">
    {{inputVal}}
    <input type="text" v-model="inputVal">
  </div>
</template>


computed: {
    ...mapState(['inputVal', ]),
  },

当前我们去改inputVal 时,会报以下错误。
在这里插入图片描述

方案一

那么如何实现 vuex 的数据双向绑定呢?一共两种方案,我们先看方案一。方案一是利用v-model 的原理,value绑定和input事件实现数据双向绑定。

store/index.js

state: {
    inputVal: '默认值',
  },

  //专门用来修改状态值的方法集合
  //mutations内的函数不支持异步函数
  mutations: {
    changeData(state, v) {
      state.inputVal = v
    },
  },

Component

<h2>方案一</h2>
    {{inputVal}}
    <input type="text" :value="inputVal" @input="updateMessage" name="" id="">


methods: {
    updateMessage(e) {
      this.$store.commit('changeData', e.target.value)
    }
  }

在这里插入图片描述

方案二

这种方式遵循的理念是使用
computed其实可以接受两个参数:
get:当获取值时会触发
set:当修改值时会触发并有新值作为参数返回

store/index.js

state: {
    message: "默认213值",
  },
mutations: {
    changeMessage(state, v) {
      state.message = v;
    }
  },

Component

computed: {
    message: {
      get() {
        return this.$store.state.message;
      },
      set(value) {
        this.$store.commit('changeMessage', value)
      }
    }
  },

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值