黑马模板网专注企业网站模板制作,包括企业pbootcms网站模板,静态网页模板,网站源码下载,HTML网站模板等等。
免责声明:本站所有资源(模板、图片)搜集整理于互联网或者网友提供,仅供学习与交流使用,如果不小心侵犯到你的权益,请及时联系我们删除该资源。
main.js
//引入Vue
import Vue from "vue";
//引入App
import App from './App';
//关闭Vue的生产提示
Vue.config.productionTip = false;
new Vue({
el:'#app',
render: h => h(App),
});
App.vue
<template>
<div class="app">
<h1>{{ msg }}</h1>
<School/>
<Student/>
</div>
</template>
<script>
import Student from "@/components/Student";
import School from "@/components/School";
export default {
name: "App",
components: {
School,
Student,
},
data() {
return {
msg: 'helloこんにちは',
studentName: ''
}
}
}
</script>
<style>
/*
全局的样式是不需要加scoped
全局共享
*/
.app{
background: gray;
padding: 5px;
}
</style>
Student.vue
<template>
<div class="student">
<h2>姓名:{{ name }}</h2>
<h2>性别: {{ sex }}</h2>
<button @click="sendStudentName">把学生名传递给school组件</button>
</div>
</template>
<script>
import pubsub from "pubsub-js";
export default {
name: "Student",
data(){
console.log(this);
return {
name: '张三',
sex: '男',
}
},
methods:{
sendStudentName(){
// this.$bus.$emit('hello', this.name);
//发布消息
pubsub.publish('hello', this.name);
}
},
}
</script>
<style scoped>
.student{
background: orange;
padding: 5px;
margin-bottom: 10px;
}
</style>
School.vue
<template>
<div class="demo">
<h2>学校名称:{{ name }}</h2>
<h2>学校地址: {{ address }}</h2>
</div>
</template>
<script>
import pubsub from 'pubsub-js';
export default {
name: "School",
data(){
console.log(this);
return {
name: 'wust university',
address: '武汉科技大学'
}
},
mounted() {
// console.log('School', this);
// this.$bus.$on('hello', (data) => {
// console.log(`我是School组件,我收到了数据,${data}`);
// })
//订阅消息 隔空对讲机喊话
this.pubId = pubsub.subscribe('hello', (name, msg) => {
//注意这里写剪头函数this才不会丢
console.log(`有人发布了hello消息,回调被执行,data: ${msg}`);
});
},
beforeDestroy() {
// this.$bus.$off('hello'); //销毁解绑
//取消订阅
pubsub.unsubscribe(this.pubId); //取消订阅
}
}
</script>
<style scoped>
/*scoped代表局部的*/
.demo{
background: skyblue;
padding:5px
}
</style>