VueJs 3 - 自定义输入组件
VueJs 3 - Custom Input Component
我正在尝试为 VueJS3 构建自定义 HTML <input>
组件。我一直在学习本教程:
https://dev.to/viniciuskneves/vue-custom-input-bk8
到目前为止,我设法让 CustomInput.vue
组件工作并将修改后的值发送回父级 App.Vue。
<template>
<label>
{{ label }}
<input type="text" :name="name" :value="value" @input="onInput" @change="onChange" />
</label>
</template>
<script>
export default {
name: 'CustomInput',
props: {
label: {
type: String,
required: true,
},
value: {
type: String,
required: true,
},
},
computed: {
name() {
return this.label.toLowerCase();
},
},
methods: {
onInput(event) {
this.$emit('input', event.target.value);
},
onChange(event) {
this.$emit('change', event.target.value);
},
},
}
</script>
我不明白的是 - 父 App.vue 组件如何检测发出的事件?我看不到它发生,我在教程中找不到它。
我的 App.Vue
看起来像这样:
<template>
<custom-input :label="'Name'" :value="name"></custom-input>
<div>{{ name }}</div>
</template>
<script>
import customInput from "./components/CustomInput.vue";
export default {
components: { customInput },
name: "App",
data: function () {
return {
name: "",
};
},
mounted() {
this.name = "Thomas";
},
};
</script>
在此先感谢您的帮助:-)
您可以直接在模板中完成。
<custom-input :label="'Name'" :value="name" @change='name=$event' @input='name=$event'></custom-input>
您也可以使用 setter 的方法或计算。
本教程适用于 Vue 2 - 对于 Vue 3,还有另一个教程 (https://www.webmound.com/use-v-model-custom-components-vue-3/)
发射 input
事件仅在 Vue 2 中有效 - 对于 Vue 3,您将必须发射 update:modelValue
并使用 modelValue
作为道具,而不仅仅是 value
.
我正在尝试为 VueJS3 构建自定义 HTML <input>
组件。我一直在学习本教程:
https://dev.to/viniciuskneves/vue-custom-input-bk8
到目前为止,我设法让 CustomInput.vue
组件工作并将修改后的值发送回父级 App.Vue。
<template>
<label>
{{ label }}
<input type="text" :name="name" :value="value" @input="onInput" @change="onChange" />
</label>
</template>
<script>
export default {
name: 'CustomInput',
props: {
label: {
type: String,
required: true,
},
value: {
type: String,
required: true,
},
},
computed: {
name() {
return this.label.toLowerCase();
},
},
methods: {
onInput(event) {
this.$emit('input', event.target.value);
},
onChange(event) {
this.$emit('change', event.target.value);
},
},
}
</script>
我不明白的是 - 父 App.vue 组件如何检测发出的事件?我看不到它发生,我在教程中找不到它。
我的 App.Vue
看起来像这样:
<template>
<custom-input :label="'Name'" :value="name"></custom-input>
<div>{{ name }}</div>
</template>
<script>
import customInput from "./components/CustomInput.vue";
export default {
components: { customInput },
name: "App",
data: function () {
return {
name: "",
};
},
mounted() {
this.name = "Thomas";
},
};
</script>
在此先感谢您的帮助:-)
您可以直接在模板中完成。
<custom-input :label="'Name'" :value="name" @change='name=$event' @input='name=$event'></custom-input>
您也可以使用 setter 的方法或计算。
本教程适用于 Vue 2 - 对于 Vue 3,还有另一个教程 (https://www.webmound.com/use-v-model-custom-components-vue-3/)
发射 input
事件仅在 Vue 2 中有效 - 对于 Vue 3,您将必须发射 update:modelValue
并使用 modelValue
作为道具,而不仅仅是 value
.