Vue3组件通信方式 v-model 通信

在子组件中,v-model会将modelValue prop和update:modelValue event绑定在一起,当子组件的input事件触发时会emit一个update:modelValue event,从而更新父组件的message。而在父组件中,v-model会将message与modelValue prop和update:modelValue event绑定在一起,当父组件更新message时,会通过modelValue prop将message传递给子组件,在子组件中输入内容时,会通过update:modelValue event将新的内容传递给父组件更新message。这样就实现了父子组件之间的数据同步。

父组件

js 复制代码
<template>
  <div>
    <h1>v-model:钱数{{ money }}{{pageNo}}{{pageSize}}</h1>
    <input type="text" v-model="info" />
    <hr />
    <!-- props:父亲给儿子数据 -->
    <!-- <Child :modelValue="money" @update:modelValue="handler"></Child> -->
    <!-- 
       v-model组件身上使用
       第一:相当有给子组件传递props[modelValue] = 10000
       第二:相当于给子组件绑定自定义事件update:modelValue
     -->
    <Child v-model="money"></Child>
    <hr />
    <Child1 v-model:pageNo="pageNo" v-model:pageSize="pageSize"></Child1>
  </div>
</template>

<script setup lang="ts">
//v-model指令:收集表单数据,数据双向绑定
//v-model也可以实现组件之间的通信,实现父子组件数据同步的业务
//父亲给子组件数据 props
//子组件给父组件数据 自定义事件
//引入子组件
import Child from "./Child.vue";
import Child1 from "./Child1.vue";
import { ref } from "vue";
let info = ref("");
//父组件的数据钱数
let money = ref(10000);
//自定义事件的回调
const handler = (num) => {
  //将来接受子组件传递过来的数据
  money.value = num;
};

//父亲的数据
let pageNo = ref(1);
let pageSize = ref(3);
</script>

<style scoped>
</style>

子组件可以在<script setup>中使用defineEmits和defineProps来定义props和event。使用v-model时需要定义一个名为modelValue的prop和一个update:modelValue的event

js 复制代码
<template>
  <div class="child2">
    <h1>同时绑定多个v-model</h1>
    <button @click="handler">pageNo{{ pageNo }}</button>
    <button @click="$emit('update:pageSize', pageSize + 4)">
      pageSize{{ pageSize }}
    </button>
  </div>
</template>

<script setup lang="ts">
let props = defineProps(["pageNo", "pageSize"]);
let $emit = defineEmits(["update:pageNo", "update:pageSize"]);
//第一个按钮的事件回调
const handler = () => {
  $emit("update:pageNo", props.pageNo + 3);
};
</script>

<style scoped>
.child2 {
  width: 300px;
  height: 300px;
  background: hotpink;
}
</style>
相关推荐
o***Z4481 天前
前端性能优化案例
前端
张拭心1 天前
前端没有实际的必要了?结合今年工作内容,谈谈我的看法
前端·ai编程
姜太小白1 天前
【前端】CSS媒体查询响应式设计详解:@media (max-width: 600px) {……}
前端·css·媒体
weixin_411191841 天前
flutter中WebView的使用及JavaScript桥接的问题记录
javascript·flutter
HIT_Weston1 天前
39、【Ubuntu】【远程开发】拉出内网 Web 服务:构建静态网页(二)
linux·前端·ubuntu
百***06011 天前
SpringMVC 请求参数接收
前端·javascript·算法
天外天-亮1 天前
Vue + excel下载 + 水印
前端·vue.js·excel
起个名字逛街玩1 天前
前端正在走向“工程系统化”:从页面开发到复杂产品架构的深度进化
前端·架构
用户47949283569151 天前
React 渲染两次:是 Bug 还是 Feature?聊聊严格模式的“良苦用心”
前端·react.js·前端框架
用户47949283569151 天前
Code Review 惊魂:同事的“优雅”重构,差点让管理员全部掉线
javascript