vue3父子组件传值

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>

posted @ 2021-06-30 20:15  兰sir  阅读(5591)  评论(2编辑  收藏  举报