继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

vue2.0组件间传值的方法汇总

MMTTMM
关注TA
已关注
手记 303
粉丝 65
获赞 364

1、组件间的传值


700

1.1 父组件向子组件传值

子组件自定义一个属性


389

父组件通过自定义属性绑定值


700

子组件调用自定义属性来拿到值


637

1.1 完)

1.2 子组件向父组件传值

子组件自定义一个事件


526

父组件通过自定义事件绑定一个方法来接收值


678


333


560

1.3 兄弟组件间传值

新建一个js文件作为兄弟组件间传值的中转站(new 一个vue)


370

组件1把值先传到bus


453

组件2从bus接收值


437


568

【完整代码】

parent.vue(父组件)

import Children1 from './children1'

  import Children2 from './children2'

    export default {

        name: "parent",

      components:{

        Children1,

        Children2

      },

      data(){

          return {

            toChildren:'',

            getChildren:''

          }

      },

      methods:{

          getChildrenData(data){

            this.getChildren = data;

          }

      }

    }  body{

    background: #eee;

  }

  .container{

    width: 100%;

  }

  .header{

    width: 100%;

  }

  .main{

    width: 985px;

    margin: 50px auto;

  }

  .children1,.children2{

    width: 40%;

    height: 300px;

    margin: 0 20px;

    display: inline-block;

    background: #909399;

    color: #fff;

  }

  .getData{

    color: darkred;

    height: 50px;

  }

children1.vue 子组件1

import bus from '../eventBus/bus'

    export default {

        name: "children",

      props:['getData'],    //子组件自定义一个属性

      data(){

          return {

            toBrother:''

          }

      },

      methods:{

        dataToBrother(){

          bus.$emit('toBrother',this.toBrother)

        }

      }

    }  h1{

     height: 50px;

    color: darkred;

   }

children2.vue 子组件2

import bus from '../eventBus/bus'

    export default {

        name: "children2",

      data(){

          return {

            toParentData:'',

            dataFromBrother:''

          }

      },

      created(){

          bus.$on('toBrother',(data)=>{

            this.dataFromBrother = data;

          })

      },

      methods:{

        dataToParent(){

          this.$emit('toParent',this.toParentData)

        }

      }

    }  h1{

    height: 50px;

    color: darkred;

  }

bus.js

import Vue from 'vue'

export default new Vue



作者:IT智云编程
链接:https://www.jianshu.com/p/24d529ad6219


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP