首页 > 其他 > 详细

vue中组件间的通信

时间:2019-12-03 04:11:06      阅读:99      评论:0      收藏:0      [点我收藏+]

1.props:父组件的数据传递给子组件(数据在子组件中)

(1)在子组件中申明props,props的类型一般为数组类型

window.HomeList ={
    template,
    props:[empList]
}

(2)在父组件中,给子组件所在的标签绑定属性

<home-list :empList="empList"></home-list>

父组件的数据如下:

data(){
return {
    hobbies:[吃饭,睡觉,打豆豆,看书],
    empList:[
        {id:1,name:小梦,salary:8000},
        {id:2,name:小话,salary:2000},
        {id:3,name:小栈,salary:8000},
        {id:4,name:小琴,salary:7000},
        {id:5,name:小爱,salary:6000},
       ]
}

 

完成后子组件可以使用props中的数据。

<tr v-for="item in empList" :key="item.id">
          <td>{{item.id}}</td>
          <td>{{item.name}}</td>
          <td>{{item.salary}}</td>
         
 </tr>

 2.props 传递函数

(1)所传递的函数写在父组件中,并在给子组件所在的标签绑定属性

methods: {
        del(index){
            this.empList.splice(index,1)
        }
    }

 

<home-list :del="del"></home-list>

 

(2)在子组件中申明props,接收父组件传递过来的函数名

(3)在子组件中的methods中写上方法,在方法的函数体内调用props中的函数

window.HomeList ={
    template,
    props:[‘del‘],
    methods: {
        deleteItem(){
            this.del()
        }
    },
}

 

 (4)在子组件中,添加触发事件

 <td><a href="#" @click.prevent="del(index)">删除</a></td>

 3.自定义事件

(1)在父组件中定义函数

methods: {
        
        delHobby(index){
            this.hobbies.splice(index,1)
        }
    },

(2)在父组件中,给子组件所在的标签绑定事件

<dashboard @delHobby="delHobby"></dashboard>

(3)在子组件中,methods中通过$emit触发传递过来的函数

methods: {
    delHobby(index){
      this.$emit(delHobby,index)
    }

(4)在子组件中添加点击事件

<a href="#" @click.prevent="delHobby(index)">删除</a>

 

 4.插槽 slot  将标签传递给子组件

(1)在子组件申明插槽的位置

<slot name="dashboard"></slot>

(2)在父组件中,子组件的标签体内添加传入的标签

<app-right>
     <h1 class="page-header" slot="dashboard">仪表盘</h1> 
</app-right>

 

vue中组件间的通信

原文:https://www.cnblogs.com/zhaodz/p/11973742.html

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