$emit组件通讯

vue2

在vue2中的写法:

<!-- 子组件 -->
<template>
    <div>
        <button @click="emitSomeThing">发送</button>
    </div>
</template>
<script>
export default {
    methods: {
        emitSomeThing() {
            this.$emit('change', '子组件传递的数据')
        }
    }
}
</script>
<!-- 父组件 -->
<template>
    <div>
        <Child @change="onChange"></Child>
    </div>
</template>
<script>
export default {
    methods: {
        // 接收子组件传递的数据
        onChange(event) {
            console.log(event) 
        }
    }
}
</script>


Mr.PDG小于 1 分钟Vue3$emit组件通讯emitdefineEmit
props组件通讯

vue2

vue2中的props写法:

<!-- 父组件 -->
<template>
    <div>
        <Child :list="list"></Child>
    </div>
</template>
<script>
export default {
    data(){
        return {
            list: [1, 2, 3]
        }
    }
}
</script>
<!-- 子组件 -->
<template>
    <div>
        <span v-for="item in list" :key="item">{{item}}</span>
    </div>
</template>
<script>
export default {
    props: {
        list: {
            type: Array,
            default: () => []
        }
    },
    mounted() {
        console.log(this.list)
    }
}
</script>

Mr.PDG小于 1 分钟Vue3props组件通讯defineProps
refs组件通讯

使用API选项时,我们可以通过this.$refs.name获取指定的元素或组件,但在组合API中不行。如果我们想通过ref获取,需要定义一个同名的Ref对象,在组件挂载后可以访问。

示例代码如下:

<template>
  <ul class="parent list-group">
    <li class="list-group-item" v-for="i in childRefs?.list" :key="i">
      {{ i }}
    </li>
  </ul>
  <!-- The value of the child component ref is the same as that in the <script> -->
  <child-components ref="childRefs"></child-components>
  <!-- parent component -->
</template>
<script setup>
import { ref } from 'vue'
import ChildComponents from './child.vue'
const childRefs = ref(null)
</script>

Mr.PDG小于 1 分钟Vue3refs组件通讯defineExpose