• Vue组件通信方式


    1.props通信

    1.1在 Vue 2 中使用 props 通信

    注意:props传递的数据是只读的,子组件修改,不会影响父组件

    1.1.1.定义 props

    子组件中使用 props 选项来定义要接收的属性

    1. // 子组件
    1.1.2.传递props

    父组件中使用子组件时,通过将属性绑定到子组件的属性名来传递数据。

    1. // 父组件
    2. <script>
    3. import ChildComponent from './ChildComponent.vue';
    4. export default {
    5. components: {
    6. ChildComponent
    7. },
    8. data() {
    9. return {
    10. parentMessage: 'Hello from parent!'
    11. };
    12. }
    13. }
    14. script>
    1.1.3.接收props
    1. // 子组件
    2. <script>
    3. export default {
    4. props: {
    5. message: String
    6. }
    7. }
    8. script>

    1.2在Vue3中使用props通信

    Vue 3 中,props 的使用方式与 Vue 2 类似,但有一些额外的特性,如默认值和类型校验的语法略有不同。

    1.2.1.定义props
    1. // 子组件
    1.2.2.传递props
    1. // 父组件
    2. <script setup>
    3. import ChildComponent from './ChildComponent.vue';
    4. const parentMessage=ref('Hello from parent!')
    5. script>
    1.2.3.接收props
    1. // 子组件
    2. <script setup>
    3. const props = defineProps({
    4. message: String
    5. });
    6. //或者
    7. const props = defineProps(['message']);
    8. script>

    2.自定义事件

    2.1在vue2中使用自定义事件

    2.1.1.触发自定义事件

    在子组件中,使用 $emit 方法触发一个自定义事件。

    1. // 子组件
    2. <script>
    3. export default {
    4. methods: {
    5. emitCustomEvent() {
    6. this.$emit('custom-event-name', eventData);
    7. }
    8. }
    9. }
    10. script>
    2.1.2.监听自定义事件

    在父组件中,通过在子组件上使用 v-on(或简写为 @)来监听自定义事件。

    1. // 父组件
    2. <script>
    3. import ChildComponent from './ChildComponent.vue';
    4. export default {
    5. components: {
    6. ChildComponent
    7. },
    8. methods: {
    9. handleCustomEvent(eventData) {
    10. // 处理自定义事件触发的逻辑
    11. }
    12. }
    13. }
    14. script>

    2.2在 Vue 3 中使用自定义事件通信

    2.2.1.触发自定义事件

    在子组件中,首先,我们导入了 defineEmits 函数,然后使用它来定义可触发的自定义事件,就像之前的示例一样。接下来,我们创建了 emitCustomEvent 函数来触发自定义事件。请注意,eventData 是事件数据的占位符,您可以根据需要替换为实际的事件数据。

    1. <script setup>
    2. import { defineEmits } from 'vue';
    3. // 使用 defineEmits 定义可触发的自定义事件
    4. const emits = defineEmits(['custom-event-name']);
    5. // 创建一个函数来触发自定义事件
    6. const emitCustomEvent = () => {
    7. emits('custom-event-name', eventData);
    8. };
    9. script>
    2.2.2.监听自定义事件

    我们在父组件的