首页的当前城市和城市选择页面的当前城市联动
使用vuex管理两个页面的都用到的数据,之前都是同一个页面的父子组件通讯。
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
1.创建一个store文件夹,存放页面共享的数据
每一个 Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
city: '上海'
},
mutations: {
changeCity (state, city) {
state.city = city
}
}
})
2.Home页使用
Home.vue中,把city
属性删除
<home-header></home-header>
HomeHeader.vue中
<div class="header-right">
{{this.$store.state.city}}
<span class="iconfont arrow-icon"></span>
</div>
3.City页使用
<div class="title border-topbottom">当前城市</div>
<div class="button-list">
<div class="button-wrapper">
<div class="button">{{this.$store.state.city}}</div>
</div>
</div>
</div>
4.点击热门城市,首页和城市选择页面的当前城市同时变化
<div class="title border-topbottom">热门城市</div>
<div class="button-list">
<div class="button-wrapper" v-for="item in hotCities" :key="item.id"
@click="handleCityClick(item.name)">
<div class="button">{{item.name}}</div>
</div>
</div>
通过commit
方法触发mutations
,改变store
中state
存放的city
值;
通过编程式路由$router
实现点击热门城市后自动跳转到首页
methods: {
handleCityClick (city) {
this.$store.commit('changeCity', city)
this.$router.push('/')
}
},