簡體   English   中英

如何在 vue 3 中實現可重用的組件輸入?

[英]How to implement reusable component input in vue 3?

誰能給我一個關於 vue 3 中可重用組件輸入的提示? 在 React 中是這樣的:

比方說,

  1. 在父組件中使用<Input />可重用組件
import { useState } from 'react';
import Input from './component/Input';

function Home() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    
    console.log(email, password);
  }

  return (
    <form onSubmit={handleSubmit}>
      <Input id="email" labelText="Email" value={email} onChange={e => setEmail(e.target.value)} />
      <Input id="password" labelText="Password" value={password} onChange={e => setPassword(e.target.value)} />
      <button type="submit">Login</button>
    </form>
  );
}
  1. 這里的<Input />組件:
export default function Input(props) {
  const { id, labelText, value, onChange } = props;

  return (
    <label htmlFor={id}>{labelText}<label>
    <input id={id} value={value} onChange={onChange}>
  );
}

您應該閱讀Vue 3 文檔中的組件基礎知識

關鍵概念:

  • 使用v-bind指令(或:速記前綴)進行數據綁定
  • 對事件處理程序使用v-on指令(或速記的@前綴)
  • 使用 雙花括號對數據屬性進行字符串插值
  • 使用v-model指令進行雙向數據綁定
  • 使用props選項聲明屬性
  • 使用ref使用Composition API創建數據屬性

Vue 3 中的等效輸入組件:

<template>
  <label :for="id">{{ labelText }}</label>
  <input
    :value="modelValue"
    @change="$emit('update:modelValue', $event.target.value)"
    :id="id"
  />
</template>

<script>
export default {
  props: {
    id: String,
    labelText: String,
    modelValue: String,
  },
};
</script>

和形式:

<template>
  <form @submit="handleSubmit">
    <MyInput id="email" labelText="Email" v-model="email" />
    <MyInput id="password" labelText="Password" v-model="password" />
    <button type="submit">Login</button>
  </form>
</template>

<script>
import MyInput from "@/components/MyInput.vue";
import { ref } from "vue";

export default {
  components: {
    MyInput,
  },
  setup() {
    const email = ref("");
    const password = ref("");

    return {
      email,
      password,
      handleSubmit(e) {
        e.preventDefault()
        console.log("submit", email.value, password.value);
      },
    };
  },
};
</script>

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM