我有以下 Vue 组件,当输入更改时,它会显示保存和取消输入组插件。谁能解释一下为什么当 textChanged 值更改时按键会从输入中丢失以及如何修复它?
<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
}
},
})
最佳答案
因此,根据 @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)
}
}
});
关于javascript - Vue 组件丢失第一次按键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47433719/