vue 父子组件通信

vue实现父子组件通信
通过一些demo来进行练习尝试

demo结构:
App.vue引用parent.vue parent.vue引用child.vue

//app.vue
<template>
  <div id="app">
    <!-- vue的命名规范,我在组件中注册是用的MParent,引用的时候需要使用-进行隔开 -->
    <m-parent></m-parent>
  </div>
</template>

<style>

</style>

<script>
import MParent from "./views/Parent.vue";
export default {
  components: {
    MParent,
  },
}
</script>
//Parent.vue
<template>
    <div>
        <h1>parent</h1>
        <m-child></m-child>

    </div>
</template>

<script>
import MChild from "./Child.vue"
    export default {
        components: {
            MChild,
        },
    }
</script>

<style scoped>

</style>
//Child.vue
<template>
    <div>
        <h3>child</h3>

    </div>
</template>

<script>
    export default {
        
    }
</script>

<style scoped>

</style>

父组件传递给子组件

在父组件中编写需要传递的数据

<h1>parent</h1>
<m-child msg ="from parent msg"></m-child>

子组件使用props进行接收
并且在创建一个标签进行数据显示

//创建h5标签来进行显示
<h3>child</h3>
<h5>{{msg}}</h5>

//使用props进行接收
<script>
    export default {
        props:{
            msg:{
                type:String,
                default:''
            }
        }

    }
</script>

子组件传递给父组件

使用$emit来进行传递
首先在子组件中设置需要传递的值,我们设置一个按钮来进行传递

<button @click="passMsg">走你</button>
//定义方法
methods: {
            passMsg() {
                this.$emit('showMsg','i am from child')
            }
        },

然后在父组件中,我们使用@加关键字来进行一个监听

<m-child :msg ="'from parent msg'" @showMsg="showMsg"></m-child>

定义一个空的msg来进行接收替换

data() {
            return {
                msg:''
            }
        },
        methods: {
showMsg(val) {
                this.msg = val
            }
        },
//在网页上进行显示
<h3>{{msg}}</h3>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值