首页 > 其他 > 详细

vue3父子组件传值

时间:2021-06-30 21:02:09      阅读:537      评论:0      收藏:0      [点我收藏+]

vue3父子组件传值

父组件向子组件传值

父组件通过v-bind绑定一个数据,然后子组件通过props接受传过来的值,跟vue2父子组件传值差不多

father.vue

<template>
<div>
    <Son :father="father" />
</div>

</template>
<script>
import { ref } from ‘@vue/reactivity‘
import Son from ‘./Son.vue‘

export default {
  components: {
    Son
  },
  setup () {
    const father = ref(‘我是父组件我要在子组件显示‘)
    return {
      father
    }
  }
}
</script>

son.vue

<template>
    <div class="son">{{father}}</div>
</template>
<script>
export default {
  props: [
    ‘father‘
  ],
  setup (props, context) {
    console.log(props)
  }
}
</script>

即使setup里有props参数,上面也要通过props接受一下,否则接收不到数据,props为空

子组件向父组件传值

先在子组件里setup参数里的context里的emit解构出来然后通过emit向父组件传值

用法同vue2的$emit一样

<template>
    <div class="son">{{father}}</div>
</template>
<script>
import { ref } from ‘@vue/reactivity‘
export default {
  props: [
    ‘father‘
  ],
  setup (props, { emit }) {
    console.log(props)

    const son = ref(‘我是儿子要在巴巴里显示‘)
    emit(‘aa‘, son)
    return {
      son
    }
  }
}
</script>

父组件里通过一个自定义事件接收子组件传过来的值

<template>
<div>
    <Son @aa="write" :father="father" />
</div>

</template>
<script>
import { ref } from ‘@vue/reactivity‘
import Son from ‘./Son.vue‘

export default {
  components: {
    Son
  },
  setup () {
    const write = (e) => {
      console.log(e.value)
    }
    const father = ref(‘我是父组件我要在子组件显示‘)
    return {
      father,
      write
    }
  }
}
</script>

vue3父子组件传值

原文:https://www.cnblogs.com/lan-sir/p/14956242.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!