Vue组件之间的传值

Vue组件之间的数据传递分为四种方式

  1. 父->子:props

传递数据

 传递其他类型的数据:

 传递函数:除了传递数据,还可以传递函数,就是子组件调用父组件的方法,如下所示:

2、子->父:$emit

子组件:

<template>
  <div>
      <button @click="sendMsgToParent">向父组件传值</button>
  </div>
</template>

<script>
  export default {
    methods: {
      sendMsgToParent:function () {
        this.$emit("childMsg","hello world!");
      }
    }
  }
</script>

父组件

<template>
  <div id="app">
    //@childMsg 与子组件中this.$emit("childMsg","hello world!")起的名字一致
    <child @childMsg="showChildMsg"></child>
  </div>
</template>

<script>
  import child from './components/Child'
  export default {
    name: "app",
    components: {
      child
    },
    methods:{
      showChildMsg:function (data) {
        console.log(data);
      }
    }
  }
</script>
  1. 插槽传递内容:slot(既可以传递数据也可以传递标签):插槽实质是对子组件的扩展,通过<slot>插槽向子组件内部指定位置传递内容。
  2. 如果想了解更多点击如下链接:Vue中组件神兵利器,插槽Slot!

  1. 非父子组件间的通信:采用第三方库来实现,如通过pubSubjs库来实现。

 

安装pubsub.js

 

发布消息:发布changeNum消息:

 

注意:订阅消息写在created里面,接收changeNum消息

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值