Vue中组件通信常用方式

组件通信常用方式:

1.props 父给子传值

// child
props: {msg: String}
// parent
<HelloWorld msg="Welocom to Your vue.js APP"/>

2.自定义事件:字给父传值

// child this.$emit('add', good)
// parent
<Cart @add="cartAdd($event)"></Cart>

3.事件总线:任意两个组件之间传值常用事件总线 或 vuex的方式。

// Bus:事件派发、监听和回调管理 class Bus{}
constructor(){ this.callbacks = {}
}
$on(name, fn){
    this.callbacks[name] = this.callbacks[name] || []
    this.callbacks[name].push(fn)
}
$emit(name, args){ if(this.callbacks[name]){
    this.callbacks[name].forEach( cb=> cb(args))}
}}
Vue.prototype.$bus = new Bus()
this.$bus.$on('foo',handle)

4.vuex

创建唯一的 全局数据管理者store,通过它管理数据并通知组件状态变更。

5.$parent/$root

兄弟组件之间同学可通过共同祖辈搭桥,$parent或$root

// brother1
this.$parent.$on('foo',handle)
// brother2
this.$parent.$emit('foo')

6.$children 父组件可以通过 $children访问子组件实现父子通信

// parent
this.$children[0].xx = 'xxx'

7.$attrs/$listeners 

 包含了父作用域中不作为prop被识别(且获取)的特定绑定(class和style除外),且可以通过v-bind = "&attrs"传入内部组件。

// child: 并未在props中声明foo
<p>{{$attrs.foo}}</p>
// parent
<HelloWorld foo="foo"/>

8.refs 获取子节点引用

// parent
<HelloWorld ref="hw"/>
mounted() { 
  this.$refs.hw.xx = 'xxx'
}

9.provide/inject 能够实现祖先和后端传值

// ancestor
provide() {
  return {foo: 'foo'}
}
// descendant
inject: ['foo']

APP.vue

<template>
  <div id="app">
    <h2>我是父组件</h2>
    <p>来用于组件的数据{{message}}</p>
    <Son1 :datas="num" @sendMsg="getDataFromSon"></Son1>
     
  </div>
</template>

<script>
import Son1 from '@/components/Son1.vue'
import Son2 from '@/components/Son2.vue'

export default {
  name: 'App',
  data() { 
    return {
      num: 4396,
      message: null
    }
  },
  components: {
    Son1,
    Son2
  },
  methods: {
    getDataFromSon(val) { 
      this.message = val
    }
  }
}
</script>
<style>

</style>

Son1.vue

<template>
  <div class="Son1">
    <button @click="sendTo">点击传递给父组件</button>
    <p>这里是显示来自于父组件的值:{{datas}}</p>
    <p>这里是显示来自于兄弟组件的值:</p>
  </div>
</template>

<script>
export default {
  name: 'Son1',
  props: ['datas'],
  data() { 
    return {
      msg: 'bug制造者',
      age: 25
    }
  },
  methods: {
    sendTo() { 
      // 通过$emit的方法将子组件的值传递给父组件
      // this.$emit('sendMsg', this.msg)
      this.$root.$emit('sendToB', this.age)
    }
  },
  mounted() { 
    this.$root.$emit('sendToB', this.age)
  }
}
</script>
<style scoped>

</style>

Son2.vue

<template>
  <div class="Son2">
    <h1>son2</h1>
    <p>这里是显示来自于父组件的值:{{msg}}</p>
  </div>
</template>

<script>
export default {
  name: 'Son2',
  data() { 
    return {
      msg: 'hello'
    }
  },
  // 页面渲染 传递
  mounted() { 
    this.$root.$on('sendToB', (value) => { 
      this.msg = value
    })
  }
}
</script>
<style scoped>

</style>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值