vue实现父子组件通信
通过一些demo来进行练习尝试
demo结构:
App.vue引用parent.vue parent.vue引用child.vue
//app.vue
<template>
<div id="app">
<!-- vue的命名规范,我在组件中注册是用的MParent,引用的时候需要使用-进行隔开 -->
<m-parent></m-parent>
</div>
</template>
<style>
</style>
<script>
import MParent from "./views/Parent.vue";
export default {
components: {
MParent,
},
}
</script>
//Parent.vue
<template>
<div>
<h1>parent</h1>
<m-child></m-child>
</div>
</template>
<script>
import MChild from "./Child.vue"
export default {
components: {
MChild,
},
}
</script>
<style scoped>
</style>
//Child.vue
<template>
<div>
<h3>child</h3>
</div>
</template>
<script>
export default {
}
</script>
<style scoped>
</style>
父组件传递给子组件
在父组件中编写需要传递的数据
<h1>parent</h1>
<m-child msg ="from parent msg"></m-child>
子组件使用props进行接收
并且在创建一个标签进行数据显示
//创建h5标签来进行显示
<h3>child</h3>
<h5>{{msg}}</h5>
//使用props进行接收
<script>
export default {
props:{
msg:{
type:String,
default:''
}
}
}
</script>
子组件传递给父组件
使用$emit来进行传递
首先在子组件中设置需要传递的值,我们设置一个按钮来进行传递
<button @click="passMsg">走你</button>
//定义方法
methods: {
passMsg() {
this.$emit('showMsg','i am from child')
}
},
然后在父组件中,我们使用@加关键字来进行一个监听
<m-child :msg ="'from parent msg'" @showMsg="showMsg"></m-child>
定义一个空的msg来进行接收替换
data() {
return {
msg:''
}
},
methods: {
showMsg(val) {
this.msg = val
}
},
//在网页上进行显示
<h3>{{msg}}</h3>