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:参数名', 改变的值)
相关推荐
步行cgn20 分钟前
JSON.stringify 详解:把 JavaScript 对象变成 JSON 字符串
开发语言·javascript·json
夜雪一千1 小时前
Linux 管道、重定向命令介绍
linux·运维·chrome
biu_biubiu1 小时前
我开源了 Codebook
前端·vue.js
yz_aiks1 小时前
chrome-use 使用教程:让 Claude Code 操控已登录的 Chrome(禅道、ONES 实测)
chrome·自动化·大模型·ai agent
super_Omni1 小时前
Chrome 插件入驻实战:从 Manifest V3 到过审上架的完整路径
大数据·前端·chrome
小李科技2 小时前
【性能优化】事件委托:目标定位与 React/Vue 实战
前端·vue.js·react.js·面试·性能优化·前端框架
蓝莓味的口香糖3 小时前
【VUE】【CSS】Vue移动端适配主流方案总结
前端·css·vue.js
上火的金鱼妹3 小时前
关于多进程sse连接通知的实战
javascript·状态模式·sse
切糕师学AI3 小时前
el-select-v2 深度解析:用虚拟滚动解决海量数据下拉选择性能瓶颈
前端·vue.js·elementui·el-select-v2
徐小夕3 小时前
JitOffice:把办公、AI 与审批装进同一个平台
前端·vue.js·github