Vue组件通信

Vue组件通信

前言

1、为什么要进行组件通信

  • 组件是一个具有独立功能的整体,但是将组件拼接在一起时,需要在这些组件之间建立联系,这个联系称之为通信

2、扩展(app的手动挂载)

new Vue({
}).$mount('#app')

一、父子组件通信

1、父子组件通信实例:

<div id="app">
	<Father></Father>  <!-- 父组件在app实例中使用-->
</div>
<template id ="father">
	<div>
		<h3>这里是父组件 </h3>
		<Son v-bind:money ='money'></Son>  
         <!-- 子组件以标签的形式嵌套在父组件的模板中-->
 	     <!-- 以单向数据绑定的形式将数据绑定在子组件身上,数据的属性名v-bind:money与下面的接收数据是同一个 -->
	</div>
</template>
<template id ="son">
	<div>
		<h3> 这里是子组件 </h3>
        <p>父亲给了我 {{money}} 钱</p>  <!--子组件使用接收的数据-->
	</div>
</template>
<script>
    Vue.component('Father',{   //创建父组件
        template:'#father',
        data(){               //定义数据,以函数的形式
            return{
                money:1000
            }
        }
    })
    
    Vue.component('Son',{   //创建子组件
        template:'#son',
        props:['money']     //在子组件的配置项中使用props接收绑定的数据,接收的这个数据是上面在父组件的模板中绑定在子组件上的属性v-bind:money,这两个要统一
        
    })

    new Vue({
        el:'#app'
    })
</script>

2、流程总结:

  • 在父组件的模板中将数据用单向数据绑定的形式,绑定在子组件身上

<Son :money = "money"/>

  • 在子组件的配置项中可以使用一个props配置项来接收这个数据,接收时,props的取值可以是一个数组也可以是其他

    Vue.component('Son',{
       template: '#son',
       props: ['money']
    })
    
    
  • 在子组件模板中,接收到的属性可以像全局变量一样直接使用

<p>父亲给了我 {{money}} 钱</p>

3、注意:

单向数据绑定的时候属性名是自定义的,但一般都需要语义化一点,通常名字和后面的属性值一致,命名的时候一般采取小写,如果接收数据和使用数据时写的的是小驼峰命名,那么在数据绑定的时候要改写成小写加-的形式。如:

  <template id="father">
    <div>
      <h3> 这里是父组件 </h3>
      <hr>
      <Son v-bind:mask-flag = "maskFlag"/>   <!--绑定时属性名写成小写加-的形式-->
    </div>
  </template>
<template id="son">
    <div>
        <h3> 这里是son组件 </h3>
      <p> {{ maskFlag }} </p>  <!--使用时就可以写成小驼峰形式-->
    </div>
  </template>
Vue.component('Father',{
    template: '#father',
    data () { 
      return {
        maskFlag: 10000000000
      }
    }
  })
  Vue.component('Son',{
    template: '#son',
    props: ['maskFlag']       //接收时也可以写成小驼峰形式   
  })

4、问题及解决

1、为什么data要定义为一个函数?

  • 组件是一个独立的个体,那么它应该拥有自己的数据,这个数据应该是一个独立的数据
  • 也就是说这个数据应该有独立作用域,也就是有一个独立的使用范围,这个范围就是这个组件内
  • js的最大特征是:函数式编程 , 而函数恰好提供了独立作用域

2、为什么data要有返回值?返回值还是一个对象?

  • 因为Vue是通过observer来观察data选项的,所有必须要有返回值

  • 因为Vue要通过es5的Object.defineProperty属性对对象进行getter和setter设置

    Vue的双向数据绑定原理是通过数据劫持和事件的发布订阅来执行的,数据劫持指的是:Vue是通过observer观察者将data选项的key和value值都设置了一个属性即es5的Object.definePropert属性对对象进行getter和setter设置

二、子父组件通信

1、子父组件通信实例:

<div id="app">
        <Father></Father>
    </div>
    <template id="father">
        <div>
            <h3> 这里是father </h3>
            <p> 儿子给了我{{money}}</p>
            <Son @give='gethongbao'></Son>

        </div>
    </template>
    <template id="son">
        <div>
            <h3> 这里是son </h3>
            <button @click="giveFather"> give </button>
        </div>
    </template>
<script>
    Vue.component('Father', {
        template: '#father',
        data() {
            return {
                money: 0
            }
        },
        methods: {
            gethongbao(val) {
                this.money = val
            }
        }

    })

    Vue.component('Son', {
        template: '#son',
        data() {
            return {
                hongbao: 1000
            }
        },
        methods: {
            giveFather() {
                this.$emit('give', this.hongbao)
            }
        }
    })

    new Vue({
        el: '#app'
    })
</script>

2、流程总结:

  • 在父组件的模板中,通过事件绑定的形式,绑定一个自定义事件在子组件身上

<Son @aa = "fn"/> //这边要注意: fn是要在父组件配置项methods中定义

  • 在子组件的配置项methods中写一个事件处理程序,在事件处理程序中触发父组件绑定的自定义事件
 Vue.component('Son', {
        template: '#son',
        data() {
            return {
                hongbao: 1000
            }
        },
        methods: {
            giveFather() {
                this.$emit('give', this.hongbao)
            }
        }
    })
  • 将子组件定义的事件处理程序 giveFather,绑定在子组件的按钮身上
<template id="son">
        <div>
            <h3> 这里是son </h3>
            <button @click="giveFather"> give </button>
        </div>
</template>

3、自定义事件:

1、通过 o n 定 义 , on定义, onemit触发

  • 自定义事件的定义(发布)

vm.$on(自定义事件的名称,自定义事件的事件处理程序)

  • 自定义事件的触发(订阅)

vm.$emit( 自定义事件的名称,自定义事件处理程序需要的参数1,参数2,参数3)

代码示例:

var vm = new Vue({
    el: '#app'
  })
vm.$on( 'aa', function () {   //自定义事件的定义
    console.log( 'aa' )
  })
vm.$emit( 'aa' )  //自定义事件的触发

2、通过绑定在组件上定义,$emit触发

<Son @aa = "fn"/>

三、非父子组件通信

1、非父子组件通信实例之ref链:

  • 通过ref绑定组件后,发现在他们的共同父组件的 $refs里面可以找到子组件
  • 弊端:ref链可以实现非父子组件的通信,但是如果层级太多,就比较繁琐了
<div id="app">
	<Father></Father>
</div>
<template id="father">
	<div>
		<h3> 这里是father </h3>
		<button @click = "look"> 点击查看父组件的this</button>
         <p>father的n:{{ n }}</p>
         <Son ref = "son"></Son>
         <Girl ref = "girl" :n = "n"></Girl>
     </div>
</template>
<template id="son">
	<div>
		<h3> 这里是son</h3>
     </div>
</template>
<template id="girl">
	<div>
		<h3> 这里是girl</h3>
         <button @click ="out"> 输出girl的this</button>
    </div>
</template>
<script>
    Vue.component('Father',{
        template:'#father',
        data(){
            return{
                n:0
            }
        },
        methods:{
            look(){
               this.n = this.$refs.son.money 
            }
        }
    })

    Vue.component('Son',{
        template:'#son',
        data(){
            return{
                money:1000
            }
        }
    })

    Vue.component('Girl',{
        template:'#girl',
        data(){
            return{
                num:0
            }
        },
        methods:{
            out(){
                console.log(this)
                console.log(this.$attrs)
            }
        }
    })

    new Vue({
        el:"#app"
    })
</script>

2、非父子组件通信实例之bus:

  • bus事件总线,我们是通过 $on来定义事件, 通过 $emit来触发事件
<div id="app">
    <Bro></Bro>
    <Sma></Sma>
</div>
<template id="big">
    <div>
      <h3> 这里是哥哥组件  </h3>
      <button @click = "hick"> 揍 </button>
    </div>
</template>

<template id="small">
    <div>
      <h3> 这里是弟弟组件 </h3>
      <p v-show = "flag"> 呜呜呜呜呜呜呜呜呜uwuwuwuwu </p>
    </div>
</template>
<script> 
var bus = new Vue() // bus原型上有  $on   $emit 

  Vue.component('Bro',{
    template: '#big',
    methods: {
      hick () {
        bus.$emit('aa')   //事件触发
      }
    }
  })

  Vue.component('Sma',{
    template: '#small',
    data () {
      return {
        flag: false
      }
    },
    mounted () { //当前组件挂载结束,也就是我们可以在页面当中看到真实dom
      // mounted这个钩子函数的触发条件是组件创建时会自动触发
      var _this = this 
      // 事件的声明
      bus.$on( 'aa',function () {
        _this.flag = true
        console.log( this )  //这里是this指的是bus, 但是我们需要的this是Sma这个组件
      })
    }
  })

  new Vue({
    el: '#app'
  })

</script>

总结:

  • 在其中一个组件的 挂载钩子函数 上 做事件的声明
Vue.component('Sma',{
     template: '#small',
     data () {
          return {
          flag: false
         }
       },
      mounted () {
          var _this = this 
          bus.$on( 'aa',function () {
               _this.flag = true
               console.log( this )
           })
       } 
  })
  • 在另一个组件中 通过bus.$emit('aa')来触发这个自定义事件

四、非常规组件通信

1、父组件将一个方法通过属性绑定的形式给了子组件,子组件先是通过props接收这个方法,再执行这个方法

  • 因为MVVM框架是单向数据流,但是此方法违背了单向数据流,所以不推荐使用
<div id="app">
    <Father></Father>
</div>
<template id="father">
    <div>
      <h3>这里是father组件</h3>
      <p> 这里是父组件的n; {{ n }} </p>
      <Son :add = "add"></Son>
    </div>
</template>
<template id="son">
    <div>
      <h3>这里是son组件</h3>
      <button @click = "add( money )"> give </button>
    </div>
</template>
<script>
Vue.component('Father',{
    template: '#father',
    data () {
      return {
        n: 0
      }
    },
    methods: {
      add ( val ) {
        this.n =  val
      }
    }
  })
  Vue.component('Son',{
    template: '#son',
    data () {
      return {
        money: 1000
      }
    },
    props: ['add']   //接收数据
  })
  new Vue({
    el: '#app'
  })
</script>

2、父组件传递一个对象类型给子组件,子组件通过 props 接收

  • 问题:子组件修改数据的时候,父组件的数据也随之改变了,因为父组件给子组件的是对象的引用地址,这种方法也不推荐使用,违背了单向数据流
<div id="app">
    <Father></Father>
</div>
<template id="father">
    <div>
      <h3>这里是father组件</h3>
      <p> father: 小金库: {{ xiaojinku.money }} </p>
      <Son :xiaojinku = "xiaojinku"></Son>
    </div>
</template>

<template id="son">
    <div>
      <h3>这里是son组件</h3>
      <button> give </button>
      <input type="text" v-model = "xiaojinku.money">   <!--这里的数据改变,父组件的数据也会改变-->
      <p> son  小金库: {{ xiaojinku.money }} </p>
    </div>
</template>
<script>
  Vue.component('Father',{
    template: '#father',
    data () {
      return {
        xiaojinku: {
          money: 1000
        }
      }
    }
  })
  Vue.component('Son',{
    template: '#son',
    props: ['xiaojinku']
  })
  new Vue({
    el: '#app'
  })
</script>
  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值