放置
keydown.enter
签入您的
InputText
而不是组件。然后,您可以执行以下操作:。
@keydown.enter="emitEnterKeyPressed()
而是在组件中。在这个
emitEnterKeyPressed()
方法,您可以
$emit
事件以及文本输入的内容,然后在父级中响应此事件:
<template>
<div>
<InputText
v-model="newTodoText"
placeholder="New todo"
@enter_key_pressed="addTodo"
/>
...
</template>
输入文本:
<template>
<input
type="text"
class="input"
v-model="v_model_text"
@keydown.enter="emitEnterKeyPressed()"
>
</template>
你的
addTodo
然后可以看起来像:
addTodo: function(input_text) {
//do something with the input_text from TextInput component
}
还有你的
emitEnterKeyPressed
看起来像:
emitEnterKeyPressed: function() {
this.$emit('enter_key_pressed', this.v_model_text);
}
之所以要这样做,是因为各个组件应该相当自主地操作,以确保可重用性。如果您需要这些组件在彼此之间进行通信,那么遵循适当的步骤是很重要的。特别是,家长与孩子之间的沟通应通过
props
观察他们价值观的变化,而孩子与家长之间的沟通应该通过
$发射
正在初始化事件(包含或不包含数据)并使用父方法处理它们。