简体   繁体   中英

Vue.js 2: Cant useTwo-way Computed Property in combination with vuex

I cant get Two-way Computed Property in combination with vuex to work.

If there are input changes I want to set getIsUnsavedData to true and "copy"/commit the changes into a new variable $store.state.authenticatedUser.changedData . After there is any change I want the input to get() its value from $store.state.authenticatedUser.changedData instead of $store.state.authenticatedUser.data to display the change.

At fist everything works like expected. If there are input changes, the changed value will be replicated in the $store.state.authenticatedUser.changedData property. The getIsUnsavedData value changes to true and the get() points to the replicated data. There is only one bug left. Suddenly the computed property never changes although the vuex store is updating correctly. The set() function still gets called, but the get() doesn't .

<ui-textbox @change="valueChanged" v-model="userName"></ui-textbox>
// ...
  computed: {
    userName: {
      get() {
        return this.$store.getters.getIsUnsavedData ? this.$store.state.authenticatedUser.changedData.name : this.$store.state.authenticatedUser.data.name
      },
      set(value) {
        this.$store.commit('setChangedUserData', {
          key: 'name',
          value: value
        })
      }
    }
  },
  methods: {
    valueChanged() {
      this.$store.commit('setUnsavedState', true)
    }
  },
// ....

实际输入值 在此处输入图片说明

Try to use mine library

https://github.com/yarsky-tgz/vuex-dot

it's done for such situations, to make code footprint of setters/getters in your code much less.

<template>
  <form>
    <input v-model="name"/>
    <input v-model="email"/>
  </form>
</template>

<script>
  import { takeState } from 'vuex-dot';

  export default {
    computed: {
      ...takeState('user')
        .expose(['name', 'email'])
        .dispatch('editUser')
        .map()
    }
  }
</script>

(updated to reflect Andor's input)

v-model can point to a computed property but it needs to handle work a bit differently than when it just refers to data.

vue's doc

applying the section on two-way computed properties:

<ui-textbox v-model="userName"></ui-textbox>
// ...
computed: {
  userName: {
    get () {
      return this.$store.state.obj.userName
    },
    set (value) {
      this.$store.commit('updateUserName', value)
    }
  }
}

I might be missing something about what you're doing but this is how I'd start to solve the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM