vue 父子组件之间的传值(通信)

79 阅读1分钟

前言

最近为了面试,重新复习了一下这些日常用的传值方法

父组件传值给子组件 props

// 父组件parent.vue
<template>
    <div>我是父组件</div>
    <son :fatherMeg=fatherMeg></son>
</template>
<script>
import son from './son'
export defalut{
    compoments:{
        son
    },
    data(){
        // 定义一个数据
        fatherMeg: '我是来自父组件的数据',
    }
}
</script>


// 子组件son.vue
<template>
    <div>我是子组件</div>
    //展示数据
    {{fatherMeg}}
</template>
<script>
export defalut{
    //接收数据 子组件接收父组件数据有两种写法
    //props:{
      //  fatherMeg:String
    //}
    props:[fatherMeg]
}
</script>

子组件给父组件传值 $emit

// 父组件parent.vue
<template>
    <div>我是父组件</div>
    <son @toParentName=getSonVal></son>
</template>
<script>
import son from './son'
export defalut{
    compoments:{
        son
    },
    data(){
        sonVal:''
    },
    methods:{
        getSonVal(data){
        this.sonVal = sonVal
            console.log('data',data)
        }
    }
}
</script>


// 子组件son.vue
<template>
    <div>我是子组件</div>
</template>
<script>
export defalut{
    data(){
        toParentVal:'给父组件传的值'
    },
    meethods:{
        toParent(){
            this.$emit('toParentName',this.toParentVal)
        }
    }
}
</script>