School.vue
<template>
<div class="school">
<h2>学校名称:{{name}}</h2>
<h2>学校地址:{{address}}</h2>
</div>
</template>
<script>
import pubsub from 'pubsub-js';
export default {
name:'TheSchool',
data() {
return {
name: '广职院',
address:'佛山'
};
},
methods: {
demo(msg_name,data){
console.log('有人发布了hello消息,hello消息的回调执行了,得到:'+data);
}
},
mounted() {
this.pub_id = pubsub.subscribe('hello',this.demo);
},
beforeDestroy() {
pubsub.unsubscribe(this.pub_id);
},
}
</script>
<style>
.school{
background-color: skyblue;
}
</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:'TheStudent',
data() {
return {
name: '张三',
sex:'男',
number:1
};
},
methods: {
sendStudentName() {
pubsub.publish('hello',this.name);
}
},
}
</script>
<style scoped>
.student{
background-color: pink;
}
</style>
App.vue
<template>
<div id="app">
<h1>{{msg}}</h1>
<student></student>
<school></school>
</div>
</template>
<script>
import School from './components/School.vue';
import Student from './components/Student.vue';
export default {
name: 'App',
components: {
School,Student
},
data() {
return {
msg: '你好啊',
};
},
}
</script>
<style scoped>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
background-color: powderblue;
margin-top: 60px;
}
</style>
main.js
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app');
index.html
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
|