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:参数名', 改变的值)
相关推荐
又是忙碌的一天33 分钟前
前端学习 JavaScript
前端·javascript·学习
右子2 小时前
微信小程序开发“闭坑”指南
前端·javascript·微信小程序
AGG_Chan2 小时前
flutter专栏--深入了解widget原理
开发语言·javascript·flutter
冰镇生鲜2 小时前
前端模拟 流式文本接口 打字机效果 mockStreamText
javascript
入秋2 小时前
Three.js后期处理实战:噪点 景深 以及色彩调整
前端·javascript·three.js
Asort2 小时前
JavaScript设计模式(七)——桥接模式:解耦抽象与实现的优雅之道
前端·javascript·设计模式
Darenm1113 小时前
JavaScript事件流:冒泡与捕获的深度解析
开发语言·前端·javascript
渣哥3 小时前
不加 @Primary?Spring 自动装配时可能直接报错!
javascript·后端·面试
@大迁世界3 小时前
第03章: Vue 3 组合式函数深度指南
前端·javascript·vue.js·前端框架·ecmascript
二十雨辰3 小时前
vite与ts的结合
开发语言·前端·vue.js