vue3使用v-model控制子组件进行双向数据绑定

vue2写法:

中父组件调用子组件:

<child :isShow.sync="isShow" v-show="isShow"/>

子组件想要消失, 在子组件写:

this.$emit("update:isShow",false);

具体代码就不粘贴了

vue3写法:

父组件核心代码:

v-model:a="xxx"

子组件核心代码:

defineProps({

a: 数据类型, // 父页面传递的数据

});

interface IEmits {

(e: 'update:a', arg1: 数据类型): void;

}

const emits = defineEmits<IEmits>();

调用父组件的方法:

emits("update:isShow", false);

使用示例:

注意: v-model:isShow="isShow" 如果拆开写就是 @update:isShow="bol=>isShow=bol" :isShow="isShow"

父组件代码如下:

复制代码
<script setup>
import { ref, defineAsyncComponent } from 'vue'

// 异步组件
const ChildA = defineAsyncComponent(() => import('./components/Test.vue'));

const isShow = ref(false);
const show = () => {
  isShow.value = true
}
</script>

<template>
  <input type="button" value="我是父组件中的按钮, 让子组件出现" @click="show">
  <!-- v-model:isShow="isShow"=> @update:isShow="bol=>isShow=bol" :isShow="isShow" -->
  <ChildA v-model:isShow="isShow" />
</template>

<style scoped>
</style>

子组件逻辑:

因为 v-model:isShow="isShow" 如果拆开写就是 @update:isShow="bol=>isShow=bol" :isShow="isShow"

所以:

defineProps({

isShow: Boolean

});

const hide = () => {

emits("update:isShow", false);

}

子组件代码如下:

复制代码
<script setup lang="ts">
// 父组件传数据 v-model:isShow="isShow"
// v-model:isShow="isShow"=> @update:isShow="bol=>isShow=bol" :isShow="isShow"
defineProps({
  isShow: Boolean
});

interface IEmits {
  (e: 'update:isShow', arg1: Boolean): void;
}
const emits = defineEmits<IEmits>();

const hide = () => { // 因为父页面传过来的方法相当于是bol=>isShow=bol, 所以传false就会消失
  emits("update:isShow", false);
}
</script>

<template>
  <div v-show="isShow">
    <button @click="hide">我是子组件,点我消失</button>
  </div>
</template>

<style scoped>
button {
  margin: 10px;
}
</style>
相关推荐
道友可好几秒前
AI 写代码太快了,快到你对齐不了它
前端·人工智能
无风听海12 分钟前
Bearer Token 权威指南:从原理到生产级安全实践
前端·javascript·安全
jerrywus19 分钟前
别只换模型!Claude Opus 4.8 努力控制 + Fast模式,真实能省钱3倍
前端·agent·claude
riuphan22 分钟前
JavaScript 类型判断完全指南
前端·javascript
Hilaku29 分钟前
前端工程师最终会变成 AI工程师?
前端·javascript·程序员
yeflx32 分钟前
Ubuntu22.04重装显卡驱动
前端·chrome
flyinmind38 分钟前
Java环境与Android环境中使用QuickJS
java·开发语言·javascript·quickjs
小二·40 分钟前
Prompt Engineering 高级技巧:CoT/ToT/ReAct 等进阶方法论实战
前端·react.js·prompt
chancygcx_41 分钟前
前端框架React day1--React入门
前端·react.js·前端框架
如烟花的信页1 小时前
数美滑块逆向分析
javascript·爬虫·python·js逆向