美文网首页
Vue父传子、子传夫通信--小案例

Vue父传子、子传夫通信--小案例

作者: _TSRed | 来源:发表于2018-05-18 15:50 被阅读0次

父传子

父组件
<template>
    <div id="app">
        父组件--{{msg}}
        <!--绑定自定义属性,变量-->
        <o-a :name="msg"></o-a>
    </div>
</template>

<script>
import oA from '@/test/A'
export default{
    data(){
        return{
            msg:'TaylorSwift',
        }
    },
    components:{
        oA
    }
}

</script>

<style scoped="scoped">
*{font-size: .5rem;}
</style>

子组件
<template>
    <div id="app">
        子组件--{{name}}
    </div>
</template>

<script>
export default{
//  接收值
    props:{
        name:{
            type:String,
            default:0
        }
    },
    data(){
        return{
            
        }
    }
}
</script>

<style>
</style>

子传夫

父组件
<template>
    <div id="app">
        父组件--{{msg}}
        <!--用on监听派发的事件,定义一个事件名-->
        <o-a v-on:child="showchild"></o-a>
    </div>
</template>

<script>
import oA from '@/test/A'
export default{
    data(){
        return{
            msg:'',
        }
    },
    components:{
        oA
    },
    methods:{
//      定义的事件名放在methods
        showchild(res){
            this.msg = res
        }
    }
}

</script>

<style scoped="scoped">
*{font-size: .5rem;}
</style>

子组件
<template>
    <div id="app">
        子组件--{{name}}
        <button @click="son">子组件</button>
    </div>
</template>

<script>
export default{
    data(){
        return{
            name:'TaylorSwift'
        }
    },
    methods:{
        son(){
//          派发事件,参数
            this.$emit("child",this.name)
        }
    }
}
</script>

<style>
</style>

如有不懂,可以看我的 Vue-组件通信

相关文章