vue 3中如何实现可复用的组件输入?

DSP*_*dav 3 javascript reactjs vue.js

任何人都可以给我有关 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>
  );
}
Run Code Online (Sandbox Code Playgroud)
  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}>
  );
}
Run Code Online (Sandbox Code Playgroud)

ton*_*y19 10

您应该阅读Vue 3 文档中的组件基础知识

关键概念:

  • 使用v-bind指令(或:速记前缀)进行数据绑定
  • 对事件处理程序使用v-on指令(或@速记前缀)
  • 使用双大括号对数据属性进行字符串插值
  • 使用v-model指令进行双向数据绑定
  • 使用props选项声明属性
  • 用于使用Composition APIref创建数据属性

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>
Run Code Online (Sandbox Code Playgroud)

以及形式:

<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>
Run Code Online (Sandbox Code Playgroud)

演示