[英]How to implement reusable component input in vue 3?
誰能給我一個關於 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>
);
}
<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.