vue父子组件传值(v-model)

父组件使用v-model传值给子组件

bash 复制代码
<template>
 
<!-- 按钮 -->
<el-button @click="addMenu('new')">打开弹框</el-button>
 
<!-- 自定义组件,下面这两种写法都可以👇 -->
<MediaDialog :name="name" v-model:visible="dialogMediaVisible" />
 
</template>
 
<script lang="ts">
import { defineComponent, ref } from 'vue'
 
export default defineComponent({
  name: 'MediaCenter',
  setup() {
    const dialogMediaVisible: Ref = ref(false)
    const name = '🚌🚌🚌🚌🚌🚌🚌🚌🚌父组件传递的name🚌🚌🚌🚌🚌🚌🚌🚌🚌'
 
    const addMenu = function(status) {
      dialogMediaVisible.value = true
    }
 
    return {
      name,
      dialogMediaVisible,
    }
  }
})
</script>

子组件

子组件使用 props 接收父组件传来的值

bash 复制代码
<template>
  <div>
    <!--⚠️注意这里有个大坑,一定要用 model-value,不能用v-model -->
    <el-dialog
      class="mediaDialog"
      title="我是一个弹框"
      :model-value="visible"
      :before-close="handleClose">
      <span>{{ name }}</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleClose">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
 
<script lang="ts">
import { defineComponent, ref, provide } from 'vue'
 
export default defineComponent({
  name: 'mediaDialog',
  props: {
    name: String,
    visible: Boolean
  },
 
  setup(props, context) {
    // 使用 context.emit('update:visible', false),改变父组件visible的值
    const handleClose = function() {
      context.emit('update:visible', false)
    }
    return { handleClose }
  }
})
</script>
 
 

注意

1)这里有个大坑,<el-dialog> 中一定要用 model-value 来代替 v-model,不能用v-model,否则会报错

(2)子组件中修改父组件传入的参数 visible 时,使用 👇方式

bash 复制代码
context.emit('update:参数名', 改变的值)
相关推荐
VX:Fegn089528 分钟前
计算机毕业设计|基于springboot + vue酒店管理系统(源码+数据库+文档)
vue.js·spring boot·课程设计
EndingCoder42 分钟前
案例研究:从 JavaScript 迁移到 TypeScript
开发语言·前端·javascript·性能优化·typescript
Irene19911 小时前
Vue3 中使用的命名规则 和 实际开发命名规范总结
vue.js·命名规范
Amumu121382 小时前
Vue脚手架(二)
前端·javascript·vue.js
lichenyang4533 小时前
从零开始构建 React 文档系统 - 完整实现指南
前端·javascript·react.js
比特森林探险记3 小时前
Hooks、状态管理
前端·javascript·react.js
比特森林探险记4 小时前
组件通信 与 ⏳ 生命周期
前端·javascript·vue.js
海绵宝龙4 小时前
Vue中nextTick
前端·javascript·vue.js
H_z_q24015 小时前
Web前端制作一个评论发布案例
前端·javascript·css
摘星编程5 小时前
React Native + OpenHarmony:useId唯一标识生成
javascript·react native·react.js