• vue组件之间的传值方式


    props

    props实现父传子

    在父组件中

     <son sondata="通过props给孩子传值"></son>
    
    • 1

    在子组件中

    props:['sondata','getprops'],
    
    • 1

    props实现子传父

    父组件
    传递一个函数给子组件

     <son :getprops="getprops"></son>
    ...
    
     methods: {
        getprops(a){
          console.log(a);
        }
      },
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    其中函数接收的值就是子组件传回的数据

    子组件
    调用这个函数

     this.getprops('要传递的值')
    
    • 1

    使用自定义事件调用函数

    自定义事件子组件给父组件传值

    方法1 使用v-on

    在父组件中定义自定义事件

    <son @get="getsonData"></son>
    
    ...
     methods: {
       getsonData(data){
        console.log(data);
       },
      },
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    其中getsonData接收的参数是子组件传递回来的参数

    在子组件中使用$emit传递给子组件

    this.$emit('get','要传递的值')
    
    • 1

    方法2 使用ref

    父组件中

    <son ref="getdata"></son>
    
    mounted() {
        this.$refs.getdata.$on('get',this.getsonData)
      },
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    子组件

    this.$emit('get','要传递的值')
    
    • 1

    全局事件总线

    可以实现任意组件之间的通信

    安装事件总线

    在main.js里面安装

    new Vue({
      render: (h) => h(App),
      beforeCreate() {
        Vue.prototype.$bus = this;
      },
    }).$mount("#app");
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    使用事件总线实现传值

    接收数据的组件中

    在组件中给$bus绑定自定义事件,事件的回调留在A组件自身。

    this.$bus.$on('bordata',(data)=>{
       console.log(data);
    })
    
    • 1
    • 2
    • 3

    回调函数的参数就是接收值

    在发送组件中

    在组件中给$bus绑定自定义事件,事件的回调留在A组件自身。

    this.$bus.$emit('bordata',数据)
    
    • 1

    消息订阅与发布(pubsub)

    也是实现任意组件之间的通信

    安装和引入pubsub

    npm i pubsub-js
    
    • 1
    import pubsub from 'pubsub-js'
    
    • 1

    提供数据
    pubsub.publish(‘xxx’,数据)

    接收数据
    this.pid = pubsub.subscribe(‘xxx’,function(消息名,接受的数据)) //订阅消息

    总结

    父传子 :props 事件总线 消息订阅与发布
    子传父 : props 组件自定义事件 事件总线 消息订阅与发布
    兄弟之间传递: 事件总线 消息订阅与发布

  • 相关阅读:
    【SpringCloud】微服务技术栈入门3 - Gateway快速上手
    AI技术产业热点分析
    Python错误与异常
    day3 力扣
    Linux open suse15==安装pcre zlib openssl nginx 关防火墙 安装httpd
    IDEA调试出现JDWP No transports initialized错误
    高低电平触发,(边沿触发)上升沿触发和下降沿触发 中断区别
    HTML: css中的display属性
    VSCode中配置C/C++环境
    欧拉路/欧拉回路
  • 原文地址:https://blog.csdn.net/ovocc/article/details/126448659