表单中的v-model

查看 https://www.yuque.com/yejielin/mypn47/xe1ml9#ts34D
组件中的v-model

相当于给这个组件一个message的属性,这个属性如果有变化,就向父组件传回来
使用
父组件APP:
<template><div><!-- 表单上使用 --><!-- <input v-model="message"><input :value="message" @input="message = $event.target.value"> --><!-- 组件上使用v-model --><hy-input v-model="message"></hy-input><!-- 相当于--><!-- <hy-input :modelValue="message" @update:model-value="message = $event"></hy-input> --><h2>{{message}}</h2></div></template><script>import HyInput from './HyInput.vue';export default {components: {HyInput},data() {return {message: "Hello World",}}}</script><style scoped></style>
子组件 HyInput
<template><div><!-- 1.默认绑定和事件处理 --><!-- <button @click="btnClick">hyinput按钮</button><h2>HyInput的message: {{modelValue}}</h2> --><!-- 2.通过input --><input :value="modelValue" @input="btnClick"><!-- 3.绑定到props中是不对的,这样双向绑定不了,不要修改props的值 --><!-- <input v-model="modelValue"> --></div></template><script>export default {props: {modelValue: String},emits: ["update:modelValue"], // 定义emits事件methods: {btnClick(event) {this.$emit("update:modelValue", event.target.value); // 变化时传到父组件}}}</script><style scoped></style>
绑定多个v-model


父组件app
<template><div><!-- 绑定两个v-model --><hy-input v-model="message" v-model:title="title"></hy-input><h2>{{message}}</h2><h2>{{title}}</h2></div></template><script>import HyInput from './HyInput.vue';export default {components: {HyInput},data() {return {message: "Hello World",title: "哈哈哈"}}}</script><style scoped></style>
子组件
<template><div><input v-model="value"><input v-model="why"></div></template><script>export default {props: {modelValue: String,title: String},emits: ["update:modelValue", "update:title"],computed: {value: {set(value) {this.$emit("update:modelValue", value);},get() {return this.modelValue;}},why: {set(why) {this.$emit("update:title", why);},get() {return this.title;}}}}</script><style scoped></style>
