Vue组件之间数据交互与通讯

Vue 的组件做用域都是孤立的,不容许在子组件的模板内直接引用父组件的数据。必须使用特定的方法才能实现组件之间的数据传递。javascript

 

1、父组件向子组件传递数据

在 Vue 中,可使用 props 向子组件传递数据。html

子组件部分:vue

若是须要从父组件获取  username  的值,就须要java

props:{
   username:{
      type:String
   }
}

示例代码git

<template>
  <div class="child01">
    my name is {{username}}
  </div>
</template>
<script>
export default {
  name: 'child01',
  props:{
    username:{
      type:String
    }
  }
}
</script>

在 props 中添加了元素以后,就不须要在 data 中再添加变量啦。github

 父组件部分:数组

示例代码this

<template>
  <div class="child01">
      <child-box :username="zuobaiquan"></child-box>
  </div>
</template>
<script>
import childBox from './child.vue'
export default {
  name: 'child01',
  data () {
    return {
      zuobaiquan:'zuobaiquan'
    }
  },
  components:{
    'child-box':childBox
  }
}
</script>

 

2、子组件向父组件传递数据

通常状况下,子组件主要经过事件传递数据给父组件spa

子组件部分:

示例代码code

<template>
  <ul class="tab-list">
    <li class="tab-li"
      v-for="(item, index) in tabItem"
      v-html="item"
      :class="{active: index === actIndex}"
      @click="handelSwitch(index)"
    >
    </li>
  </ul>
</template>
<script>
export default {
  name: 'child02',
  data(){
    return {
      tabItem:['选项一','选项二','选项三'],
      actIndex:0
    }
  },
  methods:{
    handelSwitch(index){
      this.actIndex=index;
      this.$emit("transferTabIndex",this.actIndex)
    }
  }
}
</script>

这是选项卡子组件,当tabItem的index值发生变化的时候,将 对应的tab的索引index传递给父组件

首先声明一个了方法 handelSwitch,经过点击事件click来调用 handelSwitch,在 handelSwitch方法中,使用了 $emit 来遍历 transferTabIndex事件,并传递 this.actIndex,

其中 transferTabIndex是一个自定义的事件,功能相似于一个中转站,能够把this.actIndex经过这个事件传递给父组件 

父组件部分:

在父组件parent.vue 中,声明了一个方法 getTabIndex,用 transferTabIndex事件调用 handelSwitch方法,获取到从子组件传递过来的参数 this.actIndex,传递过来的this.actIndex 能够实现 选项卡的div模块的显示与隐藏。

  注意:

  若是无需传递参数,直接写成   this.$emit(方法名);

  若是是一个参数,直接以追加参数便可;

  若是是多个参数,直接对象形式或者数组格式传递。

示例代码

<template>
  <div class="child02">
      <child-box @transferTabIndex="getTabIndex"></child-box>
      <div v-show="showIndex==0">个人选项卡1</div>
      <div v-show="showIndex==1">个人选项卡2</div>
      <div v-show="showIndex==2">个人选项卡3</div>
  </div>
</template>
<script>
import childBox from './child.vue'
export default {
  name: 'child02',
  data () {
    return {
      showIndex:0
    }
  },
  components:{
    'child-box':childBox
  },
  methods:{
    getTabIndex(index){
      this.showIndex=index;
    }
  }
}
</script>

 

3、父组件事件触发子组件

如今有这么一个需求,在父组件的某一个地方,点击 能够切换tab,这个需求也得益于公司的一个项目

https://emdatahkush5.eastmoney.com/view/financeCalendar.html#/

如图,点击 【所有】选项卡 下的 “查看更多”按钮切换到 其余的tab 页。

此时的作法是

一、父组件的button元素绑定click事件,该事件指向  tabToThree  方法

二、在 组件中 给父组件注册一个 ref="childTab"  。

三、父组件的 childTab  的方法在处理时,使用 $refs.childTab  把事件传递给子组件的  handelSwitch  方法,同时携带着父组件中的参数 index 

四、子组件接收到父组件的事件后,调用 handelSwitch 方法,把接收到的 index 放到  actIndex中,触发 tab选项卡的同步变化。

 源码地址 https://github.com/zuobaiquan/vue/tree/master/vueExercise/vue-component

相关文章
相关标签/搜索