赞
踩
历史告诉我们,痞子就算混一辈子,也还是痞子,滑头,最后只能滑自己。长得帅,不能当饭吃。
成大器者的唯一要诀,是能吃亏。
吃亏就是占便宜,原先我不信,后来我信了,相当靠谱。----《明朝那些事儿》
v-mode实现父子组件数据同步原理主要分为:
<!-- --> <template> <div> <!-- v-model用在HTML上 --> <!-- <input type="text" v-model="username"> --> <!-- <input type="text" :value="username" @input="username = (<HTMLInputElement>$event.target)!.value" /> --> <h4>账号: {{ username }}</h4> <h4>密码: {{ pwd }}</h4> <!-- v-model用在自定义组件上 --> <!-- <XinchaoInput v-model:username="username" v-model:pwd="pwd" /> --> <XinchaoInput :username="username" @update:username="username = $event" /> </div> </template> <script setup lang="ts"> import { ref, watch } from 'vue'; import XinchaoInput from './XinchaoInput.vue'; const username = ref<string>("张三") const pwd = ref<string>("123131") watch(username, (oldValue, newValue) => { console.log(newValue) }) </script> <style lang="scss" scoped> </style>
子组件
<!-- --> <template> <div> <input type="text" :value="username" @input="emit('update:username', (<HTMLInputElement>$event.target)!.value)" /> <!-- <br> <input type="text" :value="pwd" @input="emit('update:pwd', (<HTMLInputElement>$event.target)!.value)" /> --> </div> </template> <script setup lang="ts"> defineProps(['username', 'pwd']) const emit = defineEmits(['update:username', 'update:pwd']) </script> <style lang="scss" scoped> input { border: 2px solid #ccc; border-radius: 5px; padding: 2px; background-color: darkcyan; color: white; } </style>
父组件
<!-- --> <template> <div> <!-- v-model用在HTML上 --> <!-- <input type="text" v-model="username"> --> <!-- <input type="text" :value="username" @input="username = (<HTMLInputElement>$event.target)!.value" /> --> <h4>账号: {{ username }}</h4> <h4>密码: {{ pwd }}</h4> <!-- v-model用在自定义组件上 --> <XinchaoInput v-model:username="username" v-model:pwd="pwd" /> <!-- <XinchaoInput :username="username" @update:username="username = $event" /> --> </div> </template> <script setup lang="ts"> import { ref, watch } from 'vue'; import XinchaoInput from './XinchaoInput.vue'; const username = ref<string>("张三") const pwd = ref<string>("123131") watch(username, (oldValue, newValue) => { console.log(newValue) }) </script> <style lang="scss" scoped> </style>
子组件
<!-- --> <template> <div> <input type="text" :value="username" @input="emit('update:username', (<HTMLInputElement>$event.target)!.value)" /> <br> <input type="text" :value="pwd" @input="emit('update:pwd', (<HTMLInputElement>$event.target)!.value)" /> </div> </template> <script setup lang="ts"> defineProps(['username', 'pwd']) const emit = defineEmits(['update:username', 'update:pwd']) </script> <style lang="scss" scoped> input { border: 2px solid #ccc; border-radius: 5px; padding: 2px; background-color: darkcyan; color: white; } </style>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。