【问题标题】:Custom input component ignores update from method自定义输入组件忽略来自方法的更新
【发布时间】:2019-12-10 10:27:11
【问题描述】:

我做了一个自定义输入组件,它工作正常,但有一个问题:当我尝试从一个方法更新其值时,模型已更新但输入值仍然存在。

这是我的组件: https://codepen.io/ken-ramirez/pen/JgyKad

const BasicInput = {
  template: '<input v-model="content" @input="handleInput" />',
  prop: ['value'],
  data () {
    return {
      content: this.value
    }
  },
  methods: {
    handleInput (e) {
      this.$emit('input', this.content)
    }
  }
}

new Vue({
  el: '#app',
  data: { name: '' },
  components: { BasicInput },
  methods: {
    restart() {
      this.name = ''
    }
  }
})

你可以按下重启按钮看看我的意思。

【问题讨论】:

  • 你的代码有错误:props,而不是prop

标签: javascript vue.js vuejs2 binding vue-component


【解决方案1】:

就像@NikitaK 在他的回答中提到的那样,你打错字了,你应该写props 而不是prop,但我想给出一个更短的解决方案,而不使用watcher 属性,仅使用此代码@input="$emit('input',$event.target.value)"

完整示例

const BasicInput = {
  template: `<input :value="value" @input="$emit('input',$event.target.value)" />`,
  props: ['value']

}

new Vue({
  el: '#app',
  data() {
  return{
     name: ''
  }},
  components: { BasicInput },
  methods: {
    restart() {
      this.name = ''
    }
  }
})
body {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>

<div id="app">
  <basic-input v-model="name"></basic-input>
  <p>
    <strong>Name:</strong> {{ name }}
  </p>
  <button @click="restart">restart</button>
</div>

【讨论】:

    【解决方案2】:

    您的代码中有错误:props,而不是 prop

    但这还不够,您还需要手动更新您的content,它对value 属性没有反应。在data 中声明的所有内容都不会对其初始值产生反应。

    const BasicInput = {
      template: '<input v-model="content" @input="handleInput" />',
      props: ['value'],
      data () {
        return {
          content: this.value
        }
      },
      methods: {
        handleInput (e) {
          this.$emit('input', this.content)
        }
      },
      watch: {
        value(val) {
          this.content = val;
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-25
      • 2017-12-15
      • 2018-12-28
      • 2013-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-22
      相关资源
      最近更新 更多