Vue3中组件传值的方法

Vue3中组件传值的方法和Vue2中有一些区别,主要是因为Vue3采用了新的Composition API。

  1. Props传值

使用Props传递数据的方法与Vue2相同,示例如下:

// 父组件
<template>
  <child :msg="message"></child>
</template>

<script>
import Child from './Child.vue'

export default {
    
    
  components: {
    
     Child },
  data() {
    
    
    return {
    
    
      message: 'Hello Vue 3!',
    }
  },
}
</script>

// 子组件
<template>
  <div>{
    
    {
    
     msg }}</div>
</template>

<script>
export default {
    
    
  props: {
    
    
    msg: {
    
    
      type: String,
      required: true,
    },
  },
}
</script>
  1. Emit传值

使用Emit传递事件的方法与Vue2中的 e m i t 方法不同,由于 V u e 3 中并没有 emit方法不同,由于Vue3中并没有 emit方法不同,由于Vue3中并没有emit方法,因此需要通过组合api中提供的provide和inject函数来传递事件。

父组件:

<template>
  <child @increase="increment"></child>
</template>

<script>
import {
    
     ref } from 'vue'
import Child from './Child.vue'

export default {
    
    
  components: {
    
     Child },
  setup() {
    
    
    const count = ref(0)
    const increment = () => {
    
    
      count.value++
    }
    return {
    
    
      count,
      increment,
    }
  },
}
</script>

子组件:

<template>
  <button @click="increase">{
    
    {
    
     count }}</button>
</template>

<script>
import {
    
     inject } from 'vue'

export default {
    
    
  setup() {
    
    
    const increase = () => {
    
    
      // 通过provide/inject实现事件传递
      inject('increase')()
    }
    return {
    
    
      increase,
    }
  },
}
</script>

使用provide/inject配合事件的传递需要在父组件中使用provide提供一个函数,然后在子组件中使用inject来获取父组件传递的函数,在子组件中触发该函数即可触发父组件中的事件。

可以看到,Vue3中的组件传值使用了新的Composition API,通过 provide/inject 来实现数据的传递,同时也提供了更加简洁、灵活、高效的开发方式。

猜你喜欢

转载自blog.csdn.net/weixin_46286150/article/details/129946142