web 前端H5学习笔记Web前端之路

vue组件之间数据通信操作

2017-08-08  本文已影响175人  AkiraSun
image.png
<template>
  <div class="index">
    <!-- 父组件 -->
    <IndexHead  v-bind:banner-info="bannerList"></IndexHead>
  </div>
</template>
<template>
  <div class="indexhead">
      <!-- 子组件 -->
      <div  v-if="bannerInfo" v-for="banner in bannerInfo" >
      </div>
  </div>
</template>
<script>
export default {
  name: 'IndexHead',
  props:['bannerInfo'],
  data () {
      return {
        myswiper:''"
      }
    }
}
</script>
 <!-- 父组件 -->
<template>
  <component-a  v-on:child-say="listenMe"></component-a>
  <p>Do you like me? {{childWords}}</p>
</template>
 methods: {
            listenMe: function (somedata){
              this.childWords = somedata
            }
 }
 <!-- 子组件 -->
<button v-on:click="onClickMe">like!</button>

methods: {
      onClickMe: function(){
        this.$emit('child-say',this.somedata);
      }
    }
// 根组件(this.$root)
new Vue({
  el: '#app',
  router,
  render: h => h(App),
  data: {
   // 空的实例放到根组件下,所有的子组件都能调用
    Bus: new Vue()
  }
})

以下两个组件为兄弟组件,

<button @click="submit">提交<button>

methods: {
   submit() {
     // 事件名字自定义,用不同的名字区别事件
      this.$root.Bus.$emit('eventName', 123)
    }
 }
// 当前实例创建完成就监听这个事件
  created(){
    this.$root.Bus.$on('eventName', value => {
      this.print(value)
    })
  },

  methods: {
    print(value) {
      console.log(value)
    }
  },

  // 在组件销毁时别忘了解除事件绑定
  beforeDestroy() {
     this.$root.Bus.$off('eventName')
  }
上一篇 下一篇

猜你喜欢

热点阅读