Vue实现子父组件相互传递数据信息
父组件相关代码(standard2.vue):
<template>
<div id="total">
<p>{{ msg }}</p>
<div>
<router-link to="/standard1">点击跳转</router-link>
</div>
<div style="margin-top: 15px">
<el-row>
<el-button type="warning" round @click="startSend">发送给子组件</el-button>
</el-row>
</div>
<p>{{ sonSendMessage }}</p>
<!-- 子组件相关信息 -->
<standard3 :message="fatherSendMessage" @sonSendMessage="sonSend"></standard3>
</div>
</template>
<script>
// 父组件引入子组件
import standard3 from "@/components/part-2/standard3.vue";
export default {
name: 'standard2',
// 2:注册局部组件
components: {
standard3
},
data() {
return {
msg: 'Welcome to Your Vue.js App(页面布局参考规范2,父亲)',
fatherSendMessage: '',
sonSendMessage: ''
}
},
methods: {
startSend() {
this.fatherSendMessage = '这是子组件需要的数据信息';
},
sonSend(sign) {
this.sonSendMessage = sign;
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
#total {
position: absolute;
background-color: coral;
top: 110px;
left: 298px;
height: 820px;
width: 1600px;
}
</style>
子组件相关代码(standard3.vue):
<template>
<div id="total">
<p>{{ msg }}</p>
<div style="margin-top: 15px">
<el-row>
<el-button type="warning" round @click="startSend">发送给父组件</el-button>
</el-row>
</div>
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
name: 'standard3',
data() {
return {
msg: 'Welcome to Your Vue.js App(页面布局参考规范2,孩子)'
}
},
props: {
message: ''
},
methods: {
startSend() {
this.$emit('sonSendMessage', '这是父组件需要的数据信息');
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
#total {
position: absolute;
background-color: firebrick;
left: 298px;
height: 300px;
width: 1000px;
top: 300px;
}
</style>
1.父组件 → 子组件(代码解析)
首先,保证组件之间的关系(父与子):
在父组件中(standard2.vue):
// 1:父组件引入子组件
import standard3 from "@/components/part-2/standard3.vue";
// 2:注册局部组件
components: {
standard3
}
<!-- 3:子组件相关信息 -->
<standard3></standard3>
开始发送消息(子组件standard3.vue):
<p>{{ message }}</p>
// 定义
props: {
message: ''
}
开始发送消息(父组件standard2.vue):
<el-button type="warning" round @click="startSend">发送给子组件</el-button>
<!-- 子组件相关信息 -->
<standard3 :message="fatherSendMessage"></standard3>
data() {
return {
msg: 'Welcome to Your Vue.js App(页面布局参考规范2,父亲)',
fatherSendMessage: ''
}
},
methods: {
startSend() {
this.fatherSendMessage = '这是子组件需要的数据信息';
}
}
2.子组件 → 父组件(代码解析)
开始发送消息(子组件standard3.vue):
<el-button type="warning" round @click="startSend">发送给父组件</el-button>
methods: {
startSend() {
this.$emit('sonSendMessage', '这是父组件需要的数据信息');
}
}
开始发送消息(父组件standard2.vue):
<!-- 子组件相关信息 -->
<p>{{ sonSendMessage }}</p>
<standard3 @sonSendMessage="sonSend"></standard3>
data() {
return {
msg: 'Welcome to Your Vue.js App(页面布局参考规范2,父亲)',
sonSendMessage: ''
}
},
methods: {
sonSend(sign) {
this.sonSendMessage = sign;
}
}
总结
每天一个提升小技巧!!!