一、main.js
// 引入Vue
import Vue from 'vue'
// 引入app组件,它是所有组件的父组件
import App from './App.vue'
// ElementUI
import ElementUI from 'element-ui' //element-ui的全部组件
import 'element-ui/lib/theme-chalk/index.css'//element-ui的css
Vue.use(ElementUI) //使用elementUI
// 关闭vue生产提示
Vue.config.productionTip = false
// 创建vue实例对象 -- vm
new Vue({
el: "#app",
// 完成了这个功能:将APP组件放入窗口中
render: h => h(App),
beforeCreate() {
Vue.prototype.$bus = this;
}
})
2、app.vue
<template>
<div id="myapp">
<School> </School>
<br />
<Student> </Student>
</div>
</template>
<script>
// 引入组件
import School from "@/components/School.vue";
import Student from "./components/Student.vue";
// 注册组件
export default {
name: "App",
components: {
School,
Student,
},
data() {
return {
appSchoolName: "",
appAddress: "",
};
},
methods: {
getInfo(a, b) {
this.appSchoolName = a;
this.appAddress = b;
},
},
};
</script>
<style scoped>
#myapp {
border: 1px rgb(134, 0, 0) dashed;
/* height: 400px; */
padding-top: 20px;
padding-left: 10px;
/* background-color: aqua; */
}
</style>
三、School.vue(发送)
<template>
<!-- 组件一 -->
<div class="demo">
<h2>-----【School.vue】子组件-----</h2>
<h2>学校名称:{{ schoolName }}</h2>
<h2>学校地址:{{ address }}</h2>
<button @click="showName1">点击传给Student组件</button>
</div>
</template>
<script>
// 把组件暴露出去,方便引入 Vue.extend可以省略
export default {
// eslint-disable-next-line vue/multi-word-component-names
name: "School",
data() {
return {
schoolName: "清华大学",
address: "北京",
};
},
methods: {
showName1() {
this.$bus.$emit('getInfo',this.schoolName,this.address);
},
},
};
</script>
<style scoped>
.demo {
background-color: antiquewhite;
border: 1px red solid;
padding-left: 10px;
height: 250px;
width:400px;
}
button{
width:300px;
height: 50px;
/* background-color: antiquewhite; */
font-size: 22px;
}
</style>
四、Student.vue(接收)
<template>
<!-- 组件一 -->
<div class="demo">
<h2>-----【Student.vue】子组件 -----</h2>
<h2>入取该校第1名学生:{{ m_Name1 }}</h2>
<h2>入取该校第2名学生:{{ m_Name2 }}</h2>
<h2>入取该校第3名学生:{{ m_Name3 }}</h2>
<br />
<h2 style="color:red">学校名称:{{ schoolName }}</h2>
<h2 style="color:red">学校地址:{{ address }}</h2>
</div>
</template>
<script>
export default {
// eslint-disable-next-line vue/multi-word-component-names
name: "Student",
data() {
return {
m_Name1: "张三",
m_Name2: "李四",
m_Name3: "王五",
schoolName: "",
address: "",
};
},
mounted() {
this.$bus.$on("getInfo", (a,b) => {
this.schoolName=a;
this.address=b;
});
},
};
</script>
<style scoped>
.demo {
background-color: rgb(231, 231, 231);
border: 1px rgb(172, 172, 172) solid;
height: 420px;
width: 400px;
padding-left: 10px;
}
.demo button {
height: 40px;
width: 200px;
font-size: 18px;
}
</style>