1.子组件向父组件传值的方法
demo:默认内容显示是这样
通过点击子组件里的内容“我是子组件”,就显示父组件里的默认被隐藏的内容“我是父组件里的内容 ”,这条内容显示与否由子组件传的值来决定。
父组件:
<template>
<div class="parent">
<div>{{msg}}</div>
<!-- 此处是关键,用自定义事件showChild定义的方法获取子组件传递过来的值 -->
<child @showChild = "toShow"></child>
<dir v-show="son">
<div>我是父组件里的内容</div>
</dir>
</div>
</template>
<script>
import child from '../child/child'
export default {
name:'parent',
data() {
return{
msg:'我是父组件',
son:false
}
},
components:{
child
},
methods:{
toShow(val) {
this.son = val
}
}
}
</script>
<style scoped>
.parent{
width: 300px;
margin: 100px auto;
font-size: 20px;
}
</style>
子组件:
<template>
<div class="child" @click="showClick">{{msg}}</div>
</template>
<script>
export default {
name:'child',
data() {
return{
msg:'我是子组件'
}
},
components:{
},
methods:{
showClick (){
this.$emit('showChild',true) //showChild 为父组件自定义事件名,true是传的值
}
}
}
</script>
<style scoped>
.child{
width: 300px;
margin: 0 auto;
cursor: pointer;
}
</style>
子组件向父组件传值总结:
(1)在父组件中引入子组件并注册
(2)在父组件中,在引入子组件的地方添加自定义事件,自定义事件处指定一个方法,用来接收子组件传过来的值
(3)在子组件中,用this.$emit('父组件的自定义事件名',值)向父组件传值
(4)在父组件中,通过自定义事件指定的方法获取子组件传过来的值,然后拿到传过来的值在方法中就可以写你的逻辑了。注意,在dom自定义事件的方法处,无需指定参数来接收,在methods的方法里直接通过刚刚指定的方法的形参来接收子组件传的值即可。
2.父组件向子组件传值
在刚刚的基础之上直接改代码
父组件:
<template>
<div class="parent">
<div>{{msg}}</div>
<!-- 此处是关键,用自定义事件showChild定义的方法获取子组件传递过来的值,用:info向子组件传值 -->
<child @showChild = "toShow" :info="value"></child>
<dir v-show="son">
<div>我是父组件里的内容</div>
</dir>
</div>
</template>
<script>
import child from '../child/child'
export default {
name:'parent',
data() {
return{
msg:'我是父组件',
son:false,
value:'hello'
}
},
components:{
child
},
methods:{
toShow(val) {
this.son = val
}
}
}
</script>
<style scoped>
.parent{
width: 300px;
margin: 100px auto;
font-size: 20px;
}
</style>
子组件:
<template>
<div class="child" @click="showClick">{{msg}}
<div>{{info}}</div>
</div>
</template>
<script>
export default {
name: 'child',
// 子组件通过props来接收父组件传过来的值
// 我这里定的规则是 必传且是String, type需要根据你的值来变化,其他类型写法可能略有不同
props: {
info: {
type: String,
required: true
}
},
data() {
return {
msg: '我是子组件',
}
},
components: {},
methods: {
showClick() {
// showChild 为父组件自定义事件,这里要和父组件保持一致
this.$emit('showChild', true)
}
}
}
</script>
<style scoped>
.child {
width: 300px;
margin: 0 auto;
cursor: pointer;
}
</style>
父组件向子组件传值总结:父组件传值给子组件通过 : 来绑定值,子组件通过props来接收父组件绑定的那个属性,然后就可以直接使用info那个值了。
父组件:
子组件:
参考文章: