Vue组件失去了第一个按键

时间:2017-11-22 11:36:32

标签: javascript vuejs2 vue-component

我有以下Vue组件,当输入更改时显示保存和取消输入组插件。任何人都可以解释为什么当textChanged值发生变化以及如何解决时,输入中的按键丢失了吗?

JSFiddle

<div id="app">
  <my-input></my-input>
</div>

<template id="my-template">
  <div class="form-group">
    <label>Test</label>
    <div :class="{'input-group': textChanged}">
      <input type="text" class="form-control" ref="inp"
        @input="updateValue($event.target.value)" :value="value">
      <div v-show="textChanged" class="input-group-addon">Save</div>
      <div v-show="textChanged" class="input-group-addon" @click="cancel">Cancel</div>
    </div>
  </div>
</template>

new Vue({
  el: '#app'
});

Vue.component('my-input', {
  template: '#my-template',
  props: ['value'],
  mounted: function() {
    this.original = this.value || "";
  },
  methods: {
    updateValue: function(value) {
      this.textChanged = this.$refs.inp.value !== this.original;
      this.$emit('input', value);
    },
    cancel: function() {
      this.$refs.inp.value = this.original;
      this.textChanged = false;
    }
  },
  data: function() {
    return {
      original: '',
      textChanged: false
    }
  },
})

1 个答案:

答案 0 :(得分:0)

所以按照@Bert所说,我需要保存这个值。这是最后一个组件

<div id="app">
  <my-input @change="save"></my-input>
</div>

<template id="my-template">
  <div class="form-group">
    <label>Test</label>
    <div :class="{'input-group': textChanged}">
      <input type="text" class="form-control" ref="inp" v-model="current">
      <div v-show="textChanged" class="input-group-addon" @click="save">Save</div>
      <div v-show="textChanged" class="input-group-addon" @click="cancel">Cancel</div>
    </div>
  </div>
</template>

Vue.component('my-input', {
  template: '#my-template',
  props: ['value'],
  data () {
    return {
        current: "",
        original: ""
    }
  },
  mounted: function() {
    this.current = this.original = this.value || "";
  },
  methods: {
    save: function() {
      this.$emit('change', this.current);
      this.original = this.current;
    },
    cancel: function() {
      this.current = this.original;
    }
  },
  computed: {
    textChanged: function() {
    return this.original !== this.current;
    }
  }

});

new Vue({
  el: '#app',
  methods: {
    save(d) {
      //axios.post(...)
      console.log("saving: " + d)
    }
  }
});