栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > Vue.js

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

Vue.js 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

1、组件间的传值


1.1 父组件向子组件传值

子组件自定义一个属性


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


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


1.1 完)

1.2 子组件向父组件传值

子组件自定义一个事件


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




1.3 兄弟组件间传值

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


组件1把值先传到bus


组件2从bus接收值



【完整代码】

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/241208.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号