首页 > 其他 > 详细

vue组件间的通信

时间:2020-01-15 11:30:22      阅读:60      评论:0      收藏:0      [点我收藏+]

转载地址:https://juejin.im/post/5e1b37f6f265da3e51530a39

https://www.cnblogs.com/planetwithpig/p/11652798.html

1:父组件传值到子组件

父组件代码:

<child :sons="sonList"></child>
data(){
    return{
      sonsList:[‘11‘,‘22‘,‘33‘,‘44‘]
    }
  },
  components:{
    child//注册子组件
  }
子组件代码:
props:[‘sons‘],
<div v-for="(item,index) in sons" :key="index">{{item}}</div>
注意:

props 只可以从上一级组件传递到下一级组件,也就是父子组件,即这就是单向数据流

props是只读,不可以被修改,所有被修改都会失效和被警告

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

子组件

<div v-for="(item,index) in sons" :key="index" @click="emitIndex(index)">{{item}}</div>
methods:{
    emitIndex(index){
      this.$emit(‘onEmitIndex‘,index);
    }
  }
父组件
<child :sons="sonList" @onEmitIndex="onEmitIndex"></child>
<p>{{currentIndex}}</p>//展示子组件传过来的下标
data(){
    return{
      sonList:[‘小白‘, ‘小红‘, ‘小蓝‘,‘小绿‘],
      currentIndex:-1
    }
  },
  components: { child },
  methods:{
    onEmitIndex(idx){//这个idx参数是子组件this.$emit(‘onEmitIndex‘,index);
      this.currentIndex = idx;//实时刷新父组件<P>标签
    }
  }

vue组件间的通信

原文:https://www.cnblogs.com/lixihong/p/12195307.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!