vue中父子组件的相互传递

子组件从父组件那获取数据
在子组件中, 把他想要从父组件那得到的数据写在props中
在父组件中, 调用子组件像这样 <xxx :m='message'></xxx>
父组件从子组件那获取数据
在子组件中,触发函数调用this.$emit('事件名', 传递的数据)

在父组件中, 在调用子组件时  <xxx @事件名='getVal'></xxx>  注:getVal(val){this.val=val} 为method内一函数

实例如下:

实现功能介绍:点击父组件按钮设置isShow的值,传给子组件,通过判断isShow的值控制子组件是否显示,如果子组件显示则显示父组件传过来的noticeConten的值,子组件提交输入框中输入的数据给父组件显示

父组件:

<template>
<div>
<input class="notice_input" type="text" v-model="noticeContent" placeholder="父 输入框">
<button class="input_btn" @click="refWay">点击显示</button>
<notice-plugin :is-show='isShow'
:notice-content='noticeContent'
@is-show-p='getIsShow'
@son-input-m='getSonM'></notice-plugin>
<div class="show_son" v-if="isShowMe">
子给父的数据:
{{sonMessage}}
</div>
</div>
</template>

 
 
< script>
export default{
data () {
return {
noticeContent: '',
isShow: false,
isShowMe: false,
sonMessage: ''
}
},
methods: {
refWay () {
this.isShow = true
},
getIsShow (val) {
this.isShowMe = val // val就是从子组件获取的数据
},
getSonM (val) {
this.sonMessage = val // val就是从子组件获取的数据
}
}
}
</ script>
子组件:
<template>
<div class="notice_box" v-if="isShow">
<div>父给子的数据:{{noticeContent}}</div>
<div>
<input class="notice_input" type="text" v-model="sonInputM" placeholder="子 输入框">
<button class="input_btn" @click="sendToParent">点击显示</button>
</div>
</div>
</template>
 
 
< script>
export default {
name: 'notice-plugin',
props: { //存放子组件从父组件获取的数据
isShow: {
type: Boolean,
default: false
},
noticeContent: {
type: String,
default: ''
}
},
data () {
return {
isShowParent: false,
sonInputM: ''
}
},
methods: {
sendToParent () {
this.isShowParent = true
this. $emit( 'is-show-p', this.isShowParent) // 传递数据给父组件
this. $emit( 'son-input-m', this.sonInputM) // 传递数据给父组件
}
}
}
</ script>
运行结构:






猜你喜欢

转载自blog.csdn.net/m0_37747665/article/details/79095972