先画个对应关系后面的基于这个,父main子header
一、父组件传给子组件、子组件获取父组件
1. props
这种方式不支持子组件更改父组件的值,想改,这个下面有个$parent用他
//main.vue
<template>
<c-header :user="user"></c-header>//:子组件接收值="data里的值"
//要是要传的多,又有数据又想调方法,那就直接给实例传过去
<c-header :main="this"></c-header>//传实例
</template>
<script>
//先引进来路径想着改
import head from "./header"
export default {
data(){
return{
user:{
username:"haha",
password:"123"
}
}
},
methods:{
run(){
alert("我是父")
}
}
components:{
"c-header":head
}
}
</script>
//header.vue
<template>
{{user.username}}
<button @click="getUser">点我获取父组件的值</button>
{{main.user.password}}
<button @click="getMain">点我通过实例调方法</button>
</template>
<script>
export default {
data(){
return{
}
},
methods:{
getUser(){
alert(this.user.username)
},
getMain(){
this.main.run()
}
}
props:["user","main"]
//要是加验证就把props改成对象,也可以加默认值
/* props:{
title:Number
} */
}
</script>
2.$parent
支持更改父组件值
//main.vue
<template>
<c-header ></c-header>
</template>
<script>
//先引进来路径想着改
import head from "./header"
export default {
data(){
return{
user:{
username:"haha",
password:"123"
}
}
},
methods:{
run(){
alert("我是父")
}
}
components:{
"c-header":head
}
}
</script>
//header.vue
<template>
<button @click="getParentData">点我获取父组件的值</button>
<button @click="getParentFn">点我获取父组件的值</button>
</template>
<script>
export default {
data(){
return{
}
},
methods:{
getParentData(){
alert(this.$parent.user)//获取值
this.$parent.user.username="heihei"//修改值
},
getParentFn(){
this.$parent.run()
}
}
}
</script>
二、子组件传父组件、父组件获取子组件
1. $refs
支持更改子组件值
//main.vue
<template>
<c-header ref="childHeader"></c-header>
<button @click="getChildHeader">点我获取子组件的值</button>
</template>
<script>
//先引进来路径想着改
import head from "./header"
export default {
data(){
return{
}
},
methods:{
getChildHeader(){
this.$refs.childHeader.user;//获取数据
this.$refs.childHeader.getUser();//调用方法
this.$refs.childHeader.user.username="heihei";//修改值
}
}
components:{
"c-header":head
}
}
//header.vue
<template>
{{user.username}}
</template>
<script>
export default {
data(){
return{
user:{
username:"haha",
password:"123"
}
}
},
methods:{
getUser(){
alert(this.user.username)
},
}
}
</script>
2.$emit
支持更改子组件值
//main.vue
<template>
<c-header @getChild="getChild"></c-header>//@getChild自定义方法"父组件中的方法名"
</template>
<script>
//先引进来路径想着改
import head from "./header"
export default {
data(){
return{
}
},
methods:{
getChild(data){
alert(data)
}
}
components:{
"c-header":head
}
}
//header.vue
<template>
<button @click="getMain">点我执行父组件自定义方法</button>
</template>
<script>
export default {
data(){
return{
user:{
username:"haha",
password:"123"
}
}
},
methods:{
getMain(){
//没有传值的 this.$emit("getChild")
this.$emit("getChild",this.user)
},
}
}
</script>