美文网首页
vue之组件通信props/$ref和$emit

vue之组件通信props/$ref和$emit

作者: 青乌 | 来源:发表于2020-08-17 10:59 被阅读0次

prop----父组件向子组件传递数据。如自定义标题和内容
$ref----父组件调用子组件的属性和方法。

$emit----

Prop使用

父组件动态的向子组件传递数据。利用props给子组件定义属性,在父组件给属性赋值就能使子组件也具有同样的值。

//父组件main.vue
<template>
    <div>
        <img src="../../assets/img.jpeg">
        <h1>主页内容</h1>
        <child postCont="我是子内容"></child><!--静态传递数据-->
        <child :postCont="msg"></child><!--动态传递数据-->
    </div>
</template>
<script>
    import Child from './child'
    export default {
        name: "main",
        components:{
            Child
        },
        data() {
            return {
                msg:'我是子内容'
            }
        }
    }
</script>

//子组件child.vue
<template>
    <div>
        <h3>{{postCont}}</h3>
    </div>
</template>
<script>
    export default {
        name: "child",
        props:[
            'postCont'//自定义的属性名称
        ]
    }
</script>

$ref使用

ref就相当于在父组件中给子组件命名一个id,this.$refs.childid就能获取子组件,然后使用子组件的方法或者获取属性。

//父组件index.vue
<template>
    <div>
        <img src="../../assets/img.jpeg">
        <h1>我是主页面</h1>
        <child ref="childid"></child>
    </div>
</template>
<script>
    import Child from './child'
    export default {
        name: "index",
        components:{
            Child
        },
        mounted(){
            console.log(this.$refs.childid);
            this.$refs.childid.setMessage('我是子组件!');
        }
    }
</script>

//子组件
<template>
    <div>
        <h3>{{message}}</h3>
    </div>
</template>
<script>
    export default {
        name: "child",
        data() {
            return {
                message:''
            }
        },
        methods: {
            setMessage(msg) {
                this.message = msg;
            }
        }
    }
</script>

$emit使用

子组件调用到父组件的方法。

//父组件index.vue
<template>
    <div>
        <img src="../../assets/img.jpeg">
        <h1>我是父组件</h1>
        <child @close="show" v-show="isShow"></child>
    </div>
</template>
<script>
    import Child from './child'
    export default {
        name: "index",
        components: {
            Child
        },
        data() {
            return {
                message: '',
                isShow:false
            }
        },
        methods:{
            show(参数){
                this.isShow = !this.isShow;
            }
        }
    }
</script>

//子组件child.vue
<template>
    <div>
        <h3 class="msg">{{msg}}</h3>
        <button @click=hidden>点击显示子组件</button>
    </div>
</template>
<script>
    export default {
        name: "child",
        data() {
            return {
                msg: '我是子组件'
            }
        },
        methods: {
            hidden: function () {
                this.$emit('close', 参数)  //对应父组件标签@close
            }
         }
    }
</script>

相关文章

网友评论

      本文标题:vue之组件通信props/$ref和$emit

      本文链接:https://www.haomeiwen.com/subject/zdefjktx.html