博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
vue2.0组件间传值的方法汇总
阅读量:7079 次
发布时间:2019-06-28

本文共 1396 字,大约阅读时间需要 4 分钟。

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

转载地址:http://txvml.baihongyu.com/

你可能感兴趣的文章
django-关于JSON编码格式的异常处理
查看>>
debian 系统版本 划分、识别、演进 的释疑(升级系统须知)
查看>>
如何编写nagios插件
查看>>
LVS 工作原理解析
查看>>
mysql并发控制
查看>>
轻松识别Windows 2008服务器角色与功能
查看>>
Mysql及数据库的基础概念
查看>>
Gearman 基础 以及 Gearman 使用举例
查看>>
什么是BGP?使用BGP方案有什么优点
查看>>
Windows唤出桌面图标设置
查看>>
宿主机与虚拟机的相互通信
查看>>
C4D操作 延迟 ,卡顿罕见状况解决方案。
查看>>
文档linux1.2
查看>>
CentOS下如何完全卸载MySQL?解决卸载不干净的问题
查看>>
SHOW PROCESSLIST
查看>>
教你如何开启/关闭ubuntu防火墙
查看>>
一线 IT 公司开发转管理,我是怎么从 0 到 1 的?
查看>>
linux快捷键
查看>>
小编教您Springboot项目中异常拦截设计与处理
查看>>
mysql Oracle 的区别 你不能不知道的事
查看>>