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:参数名', 改变的值)
相关推荐
摘星编程1 天前
React Native for OpenHarmony 实战:Linking 链接处理详解
javascript·react native·react.js
胖者是谁1 天前
EasyPlayerPro的使用方法
前端·javascript·css
EndingCoder1 天前
索引类型和 keyof 操作符
linux·运维·前端·javascript·ubuntu·typescript
摘星编程1 天前
React Native for OpenHarmony 实战:ImageBackground 背景图片详解
javascript·react native·react.js
摘星编程1 天前
React Native for OpenHarmony 实战:Alert 警告提示详解
javascript·react native·react.js
Joe5561 天前
vue2 + antDesign 下拉框限制只能选择2个
服务器·前端·javascript
WHS-_-20221 天前
Tx and Rx IQ Imbalance Compensation for JCAS in 5G NR
javascript·算法·5g
摘星编程1 天前
React Native for OpenHarmony 实战:GestureResponderSystem 手势系统详解
javascript·react native·react.js
lili-felicity1 天前
React Native for OpenHarmony 实战:加载效果的实现详解
javascript·react native·react.js·harmonyos
ChangYan.1 天前
monorepo 多包管理识别不到新增模块,解决办法
前端·chrome