vue2.0 父子组件通讯 兄弟组件通讯

父组件是经过props属性给子组件通讯的来看下代码:vue

父组件:this

<parent>
    <child :child-com="content"></child> //注意这里用驼峰写法哦 </parent> data(){ return { content:'sichaoyun' }; }

子组件经过props来接受数据spa

第一种方法code

props: ['childCom']

第二种方法blog

props: {
    childCom: String //这里指定了字符串类型,若是类型不一致会警告的哦 }

第三种方法事件

props: {
    childCom: {
        type: String,
        default: 'sichaoyun' } }

子组件与父组件通讯字符串

vue2.0只容许单向数据传递,咱们经过出发事件来改变组件的数据,废话少说,上干货it

子组件代码class

<template>
    <div @click="open"></div> </template> methods: { open() { this.$emit('showbox','the msg'); //触发showbox方法,'the msg'为向父组件传递的数据  } }

父组件test

<child @showbox="toshow" :msg="msg"></child> //监听子组件触发的showbox事件,而后调用toshow方法  methods: { toshow(msg) { this.msg = msg; } }

兄弟组件之间的通讯

咱们能够实例化一个vue实例,至关于一个第三方

let vm = new Vue(); //建立一个新实例

组件他哥

<div @click="ge"></div> methods: { ge() { vm.$emit('blur','sichaoyun'); //触发事件 } }

组件小弟接受大哥命令

<div></div>
created() {
  vm.$on('blur', (arg) => { this.test= arg; // 接收 }); }

搞定!

相关文章
相关标签/搜索