代码之家  ›  专栏  ›  技术社区  ›  t56k

Vue:链接组件

  •  0
  • t56k  · 技术社区  · 8 年前

    如果我有 TodoList 类似这样的组件:

    <template>
      <div>
        <InputText
            v-model="newTodoText"
            placeholder="New todo"
            @keydown.enter="addTodo"
        />
      ...
    </template>
    

    如何更改 InputText 组件是否将文本发送回此组件?

    <template>
      <input
        type="text"
        class="input"
      >
    </template>
    

    这个 addTodo 方法存在,我只是不知道如何将文本链接到 输入文本 返回父零部件。

    1 回复  |  直到 8 年前
        1
  •  1
  •   B. Fleming    8 年前

    放置 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 观察他们价值观的变化,而孩子与家长之间的沟通应该通过 $发射 正在初始化事件(包含或不包含数据)并使用父方法处理它们。

    推荐文章