例如首页引用头部
header.vue 头部
<template>
<div class="header">
<p>{{headTitle}}</p>
</div>
</template>
<script>
export default {
name: "app-header",
data(){
return{
}
},
// 我是子组件,接收来自父组件的信息
props: ['headTitle'],
methods:{
}
}
</script>
App.vue
<template>
<div id="app">
<app-header v-if="header_show" :headTitle = "headerTitle"></app-header>
<router-view v-on:header="header"/>
</div>
</template>
<script>
//引用组件
import AppHeader from './components/header/header'
export default {
name: 'App',
data(){
return{
header_show:true, //判断头部是否显示
headerTitle: ""
}
},
components:{
AppHeader
},
methods:{
// 是否显示头部
header:function(bool,title){
console.log(bool,title);
this.header_show = bool;
this.headerTitle = title;
}
}
}
</script>
Index.vue 首页
<template>
<div class="hello">
test
</div>
</template>
<script>
export default {
name: 'Index',
components:{
},
data () {
return {
}
},
created:function(){
// $emit子组件调用父组件的方法并传递数据
this.$emit('header',true,"首页");
}
}
</script>