还是之前的案例,这种做法我觉得代码变得更加简洁了
在原来的基础上,这边新建了store.js文件
export default {
datalist: [],
// 订阅
subscribe(cb) {
this.datalist.push(cb)
},
// 发布 遍历
publish(value) {
this.datalist.forEach(cb => cb(value))
}
}
父组件App.vue
<template>
<div>
<Navbar></Navbar>
<Tabbar></Tabbar>
</div>
</template>
<script>
import Navbar from './Navbar.vue';
import Tabbar from './Tabbar.vue'
export default {
data() {
return {
navtitle: 'app-首页'
}
},
components: {
Navbar,
Tabbar,
}
}
</script>
<style scoped>
* {
margin: 0;
padding: 0;
}
ul {
list-style: none;
}
</style>
子组件Navbar.vue
<template>
<div>
<button>返回</button>
<span>{{ title }}</span>
<button>首页</button>
</div>
</template>
<script>
import store from './store'
export default {
//为了接收传过来的值 特定写的
data() {
return {
title: '首页'
}
},
//生命周期 钩子
mounted() {
// 订阅
store.subscribe((value) => {
console.log('qwe', value);
this.title = value
})
}
}
</script>
<style scoped>
div {
display: flex;
width: 100%;
justify-content: space-between;
height: 50px;
line-height: 50px;
background-color: #555;
}
</style>
子组件Tabbar.vue 页面的下部分
<template>
<ul>
<!-- <li v-for="data in datalist" :key="'data'">{{ data }}</li> -->
<TabbarItem v-for="data in datalist" :key="data" :item="data"></TabbarItem>
</ul>
</template>
<script>
import TabbarItem from './TabbarItem.vue';
export default {
data() {
return {
datalist: ['首页', '列表', '我的']
}
},
components: {
TabbarItem
}
}
</script>
<style>
ul {
display: flex;
position: fixed;
bottom: 0;
width: 100%;
height: 50px;
line-height: 50px;
}
li {
flex: 1;
text-align: center;
}
</style>
孙组件TabbarItem.vue
<template>
<li @click="handleClick">
{{ item }}
</li>
</template>
<script>
import store from './store';
export default {
methods: {
handleClick() {
// 发布
store.publish(this.item)
}
},
props: ['item'],
}
</script>