• vue3 父子组件间的通信


    父组件向子组件通信

    1. 父组件的内容
    <template>
      <div class="container">
        <childComponent :msg="msg">childComponent>
      div>
    template>
    
    <script setup>
    import { ref } from 'vue';
    import childComponent from '../components/childComponent.vue'
    
    const msg = ref("父组件传给子组件的值");
    
    script>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    1. 子组件的内容
    <template>
      <div class="container">
        <div>{{ msgValue }}div>
      div>
    template>
    
    <script setup>
    import { ref } from "vue"
    
    const msgValue = ref(null)
    const props = defineProps({
      msg: {
        type: String,
        default: ""
      }
    })
    msgValue.value = props.msg
    
    script>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    子组件向父组件通信

    1. 父组件的内容
    <template>
      <div class="container">
        <span>{{ childVlaue }}span>
        <childComponent @myClick="onMyClick">childComponent>
      div>
    template>
    
    <script setup>
    import { ref } from 'vue'
    import childComponent from '../components/childComponent.vue'
    
    const childVlaue = ref(null)
    
    const onMyClick = (val) => {
      childVlaue.value = val
    }
    
    script>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    1. 子组件的内容
    <template>
      <div class="container">
        <el-button type="primary" size="default" @click="handleClick">子组件向父组件通信el-button>
      div>
    template>
    
    <script setup>
    
    const emit = defineEmits(["handleClick"]);
    const handleClick = () => {
      // 触发父组件中的方法,并把值以参数的形式传过去
      // 这里触发的方法名要和父组件中@符后面的名称一样
      emit("myClick", "子组件向父组件传送的信息");
    }
    
    script>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
  • 相关阅读:
    @Validated和@Valid 区别
    10_12C++
    Java的基础语法(二)
    飞行器翼尖加速度和控制面的MPC控制
    为什么需要森林防火气象站?
    (Tekla Structures二次开发)修改工程属性
    每天五分钟机器学习:函数间隔与几何间隔以及平行和重合的问题
    uniapp 开发公众号 h5(openid,微信支付,订阅通知)
    Go SSE Demo
    电脑端微信无法打开腾讯文档
  • 原文地址:https://blog.csdn.net/bigpatten/article/details/125897637