【问题标题】:Computed property doesn't update on readonly input计算属性不会在只读输入上更新
【发布时间】:2019-05-08 04:17:38
【问题描述】:

我有一个默认设置为只读的输入字段,当您单击按钮时,应该可以编辑该项目。

没有只读字段,该字段似乎更新正确。

没有它,我编辑该项目,当焦点丢失时,它会恢复为之前的文本。

<template>
  <input ref="input"
         :readonly="!edit"
         type="text"
         v-model="inputValue"
         @blur="edit = false">
  <button @click="editItem"/>
</template>

data(){
  return {
    edit: false,
  }
}
methods: {
  ...mapMutations(['setKey']),
  editItem() {
    this.edit = true;
    this.$nextTick( () => this.$refs.input.focus() );
  }
}
computed: {
  ...mapGetters(['getKey']),
  inputValue: {
    get() {
      return this.getKey();
    }
    set(value) {
      this.setKey({value});
    }
  }
}

注意:存储已正确更新,但未触发 getter。 没有只读他会被触发。

可能是使用只读的不正确方式吗? 也试过这个而不是真/假。

:readonly="edit ? null : 'readonly'"

【问题讨论】:

    标签: vue.js vuex


    【解决方案1】:

    在我看来,有一种更好的方法来处理您的文本字段值。使用 mapGetters + mapActions。将 getter 值与 :value=inputValue 一起使用。并通过您的操作在 blur 上提交此值。顺便说一句,请不要在 html 模板 (edit = false) 中更改您的数据。 :readonlytrue/false 配合得很好。 或者你可以使用观察者。像这样的:

    v-model="inputValue",
    @blur="toggleEgit"
    
    ...
    data () {
        return {
            inputValue: this.getKey
        }
    },
    
    methods: {
        toggleEgit () {
            this.isEdit = !this.isEdit;
        }
    },
    
    watch: {
        inputValue: {
              handler: function (value) {
                  this.$commit('setKey', value) // or whatever you want to update your store
              }
        }
    }
    

    【讨论】:

    • 如您所见,我已经在使用 mapGetters 和 mapActions 来更改文本字段的值。
    • 有什么理由从 mapMutations 转移到 mapActions?问题是计算的get没有被调用,数据被正确更新了。
    • 动作是异步的,突变不是。也许你应该在你的 getter 上使用 watcher?
    • 在他们自己的例子中,他们正在使用提交,所以我不确定它是否是问题所在。但是如果没有 readonly 属性,一切正常,getter 会被调用。 vuex.vuejs.org/guide/forms.html
    • srsly,使用 watcher 而不是这个 set/get 的东西。这很简单,可能会解决您的问题
    猜你喜欢
    • 2017-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-09
    • 2014-07-21
    • 1970-01-01
    • 2019-06-18
    相关资源
    最近更新 更多