DSP*_*dav 3 javascript reactjs vue.js
任何人都可以给我有关 vue 3 中可重用组件输入的提示吗?在 React 中就像这样:
可以说,
<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)
<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选项声明属性ref创建数据属性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)