vue - 文本字段绑定值不反映实际值
vue - textfield bound value not reflecting actual value
我有一个简单的组件,它接受一个值属性并显示一个用于编辑它的文本字段。如果数字低于零,我希望它只是零,如果文本从文本字段中删除,我想要它为零。在我的 emit
事件中,我可以看到我发出了正确的值,它只是没有反映在文本字段本身中。
我有 a fiddle link here 但是,主要部分列在下面:
<div id="app">
<test-component v-model="foo"></test-component>
</div>
const TestComponent = {
props: ['value'],
template: `<div>{{value}}
<input type="number" :value="value" @input="update($event.target.value)" />
</div>`,
methods: {
update(value) {
this.$emit("input", value <= 0 ? 0 : value)
}
}
}
new Vue({
el: "#app",
components: {
'test-component': TestComponent
},
data: {
foo: 1
},
})
基本上发生的事情是我可以看到我的事件以值 0 发出,但是,您可以看到 {{value}} 反映了 prop 中的内容,但是 textfield
中的打印值本身为空(或小于零)
我在这里肯定有一些基本的误解,我认为 :value 应该反映现实,但显然不是。非常感谢任何帮助!
您需要在 TestComponent
上放置一个 key
,然后每次更新 foo 时更改密钥,这应该会触发重新渲染,这就是这里的问题。
根据@Michael 的回复,技巧是使用 key
触发重新渲染。
there's a new fiddle here ,不是特别优雅,我只是想先把它弄好:)
此处更新的元素:
<div id="app">
<test-component :key="key" :value="foo" @input="input"></test-component>
</div>
const TestComponent = {
props: ['value'],
template: `<div>
<input type="number" :value="value" @input="update($event.target.value)" />
</div>`,
methods: {
update(value) {
this.$emit("input", value <= 0 ? 0 : value)
}
}
}
new Vue({
el: "#app",
components: {
'test-component': TestComponent
},
data: {
key: 0,
foo: 1
},
methods: {
input (value) {
this.foo = value;
this.key += 1;
}
}
})
我有一个简单的组件,它接受一个值属性并显示一个用于编辑它的文本字段。如果数字低于零,我希望它只是零,如果文本从文本字段中删除,我想要它为零。在我的 emit
事件中,我可以看到我发出了正确的值,它只是没有反映在文本字段本身中。
我有 a fiddle link here 但是,主要部分列在下面:
<div id="app">
<test-component v-model="foo"></test-component>
</div>
const TestComponent = {
props: ['value'],
template: `<div>{{value}}
<input type="number" :value="value" @input="update($event.target.value)" />
</div>`,
methods: {
update(value) {
this.$emit("input", value <= 0 ? 0 : value)
}
}
}
new Vue({
el: "#app",
components: {
'test-component': TestComponent
},
data: {
foo: 1
},
})
基本上发生的事情是我可以看到我的事件以值 0 发出,但是,您可以看到 {{value}} 反映了 prop 中的内容,但是 textfield
中的打印值本身为空(或小于零)
我在这里肯定有一些基本的误解,我认为 :value 应该反映现实,但显然不是。非常感谢任何帮助!
您需要在 TestComponent
上放置一个 key
,然后每次更新 foo 时更改密钥,这应该会触发重新渲染,这就是这里的问题。
根据@Michael 的回复,技巧是使用 key
触发重新渲染。
there's a new fiddle here ,不是特别优雅,我只是想先把它弄好:)
此处更新的元素:
<div id="app">
<test-component :key="key" :value="foo" @input="input"></test-component>
</div>
const TestComponent = {
props: ['value'],
template: `<div>
<input type="number" :value="value" @input="update($event.target.value)" />
</div>`,
methods: {
update(value) {
this.$emit("input", value <= 0 ? 0 : value)
}
}
}
new Vue({
el: "#app",
components: {
'test-component': TestComponent
},
data: {
key: 0,
foo: 1
},
methods: {
input (value) {
this.foo = value;
this.key += 1;
}
}
})