vue-22-订阅与发布-复习

还是之前的案例,这种做法我觉得代码变得更加简洁了


在原来的基础上,这边新建了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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值