父子组件间的通信
一、创建子组件
-
创建全局组件
const cpn = Vue.component('cpn',{ template: '#mycpn' })
-
创建模板
<template id = "mycpn"> <div> <p>我是子组件</p> </div> </template>
-
在父组件中声明子组件
components:{ cpn }
二、父子组件通信:父传子
-
在父组件中声明要传递的数据
data:{ // fathermes : '我是父组件要传递的内容' fathermes : ['w','e','x','n'] }
-
在子组件的props属性中声明要接收变量的类型
props :{ childmes : Array }
-
在调用子组件的标签中,将父组件中的变量动态赋值给子组件变量
<cpn :childmes = "fathermes"></cpn>
-
在子组件的模板中可以使用已赋值的变量
<template id="mycpn"> <div> <h3>我是子组件</h3> <p v-for="item in childmes">{{item}}</p> </div> </template>
三、父子间的通信:子传父
-
在子组件中定义数据
data(){ //在子组件中一定使用data方法而不是data属性 return{ message : '我是子组件要传递的信息' } }
-
在子组件模板中绑定点击事件
<template id = "mycpn"> <div> <p>我是子组件</p> <button @click="deliver">deliver</button> </div> </template>
-
在事件中使用this.$emit()传值
methods :{ deliver (){ this.$emit('ok',this.message) //第一个参数是自定义名称,绑定父组件的时候要用 } //第二个是要传递的数据 }
-
在父组件中定义变量用来接收传递的数据
data :{ fatherreceive :'' },
-
在调用子组件的标签内,绑定子组件中的自定义事件和父组件的相关方法
<cpn v-on:ok="finish"></cpn> //监听自定义事件,调用方法 methods :{ finish(data){ //data是自命名参数,用来接受传递过来的值 this.fatherreceive = data; } },
-
父组件使用传递的数据
<p>{{fatherreceive}}</p>
四、子访问父
父子组件间的访问 :子访问父
子组件也可以访问父组件和根组件,由于组件的复用性,访问父组件的方法并不常用
-
创建父组件和根组件中的方法(当父组件没有父组件,则该父组件即为根组件)
methods : { //父组件的方法 fathermes(){ console.log('我是cpn的方法') } } methods :{ rootmes(){ //根组件的方法 console.log('我是app的方法') } }
-
创建监听点击事件,并访问父组件和根组件的数据或方法
<template id = "ccpn"> <div> <p>我是cpn组件的子组件</p> <button @click="ccpnClick">button</button> </div> </template> ccpnClick(){ console.log(this.$parent.fathermes()) //访问父组件 console.log(this.$root.rootmes()) //访问最底层的根组件 }
五、父访问子
父子组件间的访问 :父访问子
父组件可以通过this. c h i l d r e n 或 者 t h i s . children或者this. children或者this.refs访问子组件的数据或方法等
-
在子组件中声明数据和方法
components :{ cpn:{ template:'#mycpn', data(){ return{ message : '子组件的数据' } }, methods :{ sendMessage(){ console.log('父组件访问子组件成功啦') } } } }
-
创建监听点击事件
<div id="app"> <cpn></cpn> <cpn></cpn> <cpn ref="here"></cpn> //设置ref属性,唯一标识子组件 <button @click="btnClick">按下</button> </div>
-
调用this. c h i l d r e n 或 者 t h i s . children或者this. children或者this.refs访问子组件数据
btnClick(){ console.log(this.$children) //是一个数组,里面是子组件 this.$children[0].sendMessage() // 调用第一个子组件的sendMessage()方法,不常用 console.log(this.$refs.here.message); //访问ref为here的子组件 }