有时候我们经常分不清什么是父组件,什么又是子组件。现在来简单说下:我们将某段代码封装成一个组件,而这个组件又在另一个组件中引入,而引入该封装的组件的文件叫做父组件,被引入的组件叫做子组件。以上是我个人的理解含义,那么现在就直接上代码吧!
子组件:
<template>
<div>
{{msg}}
</div>
<p>{{hello}}</p>
<p>{{hellotests}}</p>
<button @click="btns">按钮</button>
</template>
<script>
export default{
data(){
return{
// 子组件中声明的变量
msg:'',
hello:'',
hellotests:''
}
},
created(){
},
watch:{
// 监听从父组件传过来的数据是否发生改变,然后赋值给变量
CCCount() {
this.msg = this.msgTest
this.hello = this.helloTest
}
},
methods:{
// 点击按钮,子组件操做父组件中的函数
btns(){
this.$emit('childsClick', '子组件触发父组件中的函数')
},
// 被父组件调用的子组件函数
msgs1(){
this.hellotests = '哈哈,我是父组件调用子组件的函数'
}
},
// 接收从父组件传过来的数据
props:['msgTest', 'helloTest', 'CCCount']
}
</script>
父组件:
<template>
<div>
test
</div>
<p>hello world</p>
<span>{{btnVal}}</span>
<msgChild
ref="msgRef"
@childsClick="btnClick"
:msgTest='msgTest2'
:helloTest='helloTest2'
:CCCount='CCCount'
>
</msgChild>
</template>
<script>
// 引入子组件
import msgChild from './test.vue'
export default{
data(){
return{
msgTest2:'',
helloTest2:'',
CCCount:0,
btnVal:''
}
},
components:{
// 声明子组件名字
msgChild
},
created(){
this.msgs()
},
methods:{
msgs(){
// 给子组件变量赋值
this.msgTest2 = '测试1'
this.helloTest2 = '测试2'
},
btnClick(val) {
this.CCCount++
this.btnVal = val
// 触发子组件中的函数
this.$refs.msgRef.msgs1()
}
}
}
</script>
从父组件代码可知,test.vue是子组件,并且在父组件中被命名成 msgChild ,我们在父组件中放置子组件的位置直接写子组件的名字即可,这样就是相当于放置了整个子组件。
先说父组件是怎么传值给子组件的:我们从父组件可知有这些变量,
:msgTest='msgTest2'
:helloTest='helloTest2'
:CCCount='CCCount'
例如:msgTest就是子组件接收的变量(无需再在子组件中声明),需要在子组件中的props中接收( props:['msgTest', 'helloTest', 'CCCount'] )。msgTest2是父组件的变量,需要在父组件中声明。我只需要在父组件中给msgTest2赋值即可,子组件中的this.msgTest便能接收到。
那么子组件是怎么向父组件中传值的呢?是通过触发父组件中的函数,并传递一个参数来完成传值的,例如:
this.$emit('childsClick', '子组件触发父组件中的函数')
触发父组件中的@childsClick="btnClick"来调用btnClick方法,并向btnClick方法传参 '子组件触发父组件中的函数' , 通过触发方法来向父组件传值。
父组件又是如触发子组件中的函数呢?答案是通过父组件中的 ref 来触发的,父组件中的 this.$refs.msgRef.msgs1() 便是触发子组件中的msgs1()函数。