Value passing between Vue child and parent components written before - WeiflR10's Blog - CSDN Blog
1. From father to son (prop)
Step 1: Define data in the parent component, for example: tohome
data () {
return {
tohome:"给home组件传值",
}
},
Step 2: Bind an attribute on <v-home>, for example: title
<v-home :title="tohome"></v-home>
Step 3: The child component uses props to receive the value passed from the parent component
方法一 props:{
'title':String,
'bool':Boolean,
'getFun':Function
},
方法二 props:['title','bool','getFun','parent']
Step 4: Bind the passed data on the subcomponent
<p>{
{title}}</p>
2. From son to father ($meit)
Subassembly
<template>
<div>
<span>我是子组件</span>
<button @click="btnClick">点击后给父组件传参</button>
</div>
</template>
<script>
export default {
data(){
return {
aa:'我是子组件上的信息'
}
},
methods:{
btnClick(){
this.$emit('itemfun',this.aa)
}
}
}
</script>
parent component
<template>
<div>
<span>我是父组件</span>
<v-home @itemfun='getapp'></v-home>
<span>{
{data}}</span>
</div>
</template>
<script>
import home from '../../home'
export default {
components:{
'v-home':home
},
data(){
return {
data:''
}
},
methods:{
// 获取子组件填写好的值
getapp(val){
this.data=val
}
}
}
</script>
Note: If the child component does not have a click event to pass parameters to the parent component, you can use watch to listen
Subassembly
<template>
<div>
<span>我是子组件</span>
</div>
</template>
<script>
export default {
data(){
return {
aa:''
}
},
// 监听父组件有没有获取到值
watch: {
aa: {
handler (n, o) {
this.$emit('itemfun', n);
},
deep: true
}
},
mounted(){
this.aa="我是子组件上的信息"
},
}
</script>
The content of the parent component is the same as above
3. $refs
Use this.$refs in the parent component to get all the methods and data of the child component
//子组件
<template>
<div>
<span>我是子组件</span>
</div>
</template>
<script>
export default {
data(){
return {
}
}
}
</script>
//父组件
<template>
<div>
<span>我是父组件</span>
<v-home ref="refHome"></v-home>
</div>
</template>
<script>
import home from '../../home'
export default {
components:{
'v-home':home
},
data(){
return {
data:''
}
},
mounted(){
console.log(this.$refs) //在父组件输出,可以直接获取home组件的所有数据和方法
}
}
</script>
operation result
4. $parent / $children
Note: this points to the Vue instance, so this.$parent is the parent component of this page; the same this.$children is the child component of this page;
Therefore, if you are currently in the parent component, you can access all the data and methods of the child component through this.$children; if you are currently in the child component, you can access all the data and methods of the parent component through this.$parent;
If you want to access all methods and data of subcomponent 2 in subcomponent 1, you can pass this.$parent.$refs or this.$parent.$children
In fact, there are many methods, such as scoped slots and so on. You can refer to this article
A brief summary of the method of passing parameters between Vue components