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:参数名', 改变的值)
相关推荐
MoonPointer-Byte1 小时前
[特殊字符]The Omniscient Tome | 全知之书
javascript·html5
Otto_10271 小时前
Chrome右上角图标显示有问题
chrome
无声20172 小时前
Turborepo 的 Docker 化实战
前端·vue.js
POLITE33 小时前
Leetcode 21.合并两个有序链表 JavaScript (Day 10)
javascript·leetcode·链表
止观止3 小时前
告别回调地狱:深入理解 JavaScript 异步编程进化史
javascript·ecmascript·promise·async/await·异步编程·前端进阶
+VX:Fegn08953 小时前
计算机毕业设计|基于springboot + vue在线教育学习系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·学习·课程设计
军军君013 小时前
Three.js基础功能学习四:摄像机与阴影
开发语言·前端·javascript·3d·typescript·three·三维
slongzhang_5 小时前
edge/Chrome浏览器闪屏/花屏
前端·chrome·edge
千里马-horse5 小时前
Rect Native bridging 源码分析--Class.h
javascript·react native·react.js·class
luckyCover5 小时前
Vue源码分析 - 从入口到构造函数的整体流程
前端·vue.js