vue使用localStorage以及mapState、mapActions、mapMutations等辅助函数(vue--去哪儿网)

使用localStorage

当选中某一个城市之后,如果没有使用缓存那么在刷新页面或者重新打开页面的时候,城市会变成初始化的城市,这个可以通过localStorage来解决
在用户通过mutation来改变数据的时候,可以使用localStorage来存储数据,而state的值优先从localStorage中获取

//index.js
state: {
		city: localStorage.city || '北京'
	},
mutations: {
	changeCity1 (state, city) {   //这里的changeCity1就是actions中传过来的第一个参数
		state.city = city	
		localStorage.city = city
	}
}

使用localStorage最好在外层使用try…catch,因为有的用户会关闭浏览器的存储功能,如果没有用try…catch,则js就会报错停止运行

//index.js
let defaultCity = '上海'
try {
	if(localStorage.city) {
		defaultCity = localStorage.city
	}
} catch(e){}
export default new Vuex.store({
	state: {
		city: defaultCity
	},
	mutations: {
		changeCity1(state, city){
			state.city = city
			try {
		      localStorage.city = city
		    } catch (e) {}
		}
	}
})

使用mapState等辅助函数

//header.vue
import { mapState } from 'vuex'

然后在计算属性computed中接受mapState,用计算属性是因为数据一旦发生改变则视图层可以及时变化
使用辅助函数的同时可以使用es6的对象扩展符(相当于展开)

//header.vue
computed: {
	...mapState(['city']) //这里的意思是把state中的名为city的数据映射到computed中的名为city的计算属性之中: city: city
}

使用辅助函数之后,上面获取数据的地方就不应使用this.$store.state.city,直接使用计算属性就可以:this.city

<div class="button">{{this.city}}</div>

mapState中不仅可以放数组,还可以放对象,例如:

computed: {
	...mapState({
		currentCity: 'city'
	}) //这里的意思是把state中的名为city的数据映射到computed中的名为currentCity的计算属性之中: currentCity: city
}

那么这里获取数据就应该使用this.currentCity

mapMutations

我们在列表或者热门城市的点击函数中使用了dispatch或者commit去改变state中的数据,这里vuex也同样给我们提供了一个名为mapMutations的辅助函数

import { mapState, mapMutations } from 'vuex'

然后在methods中使用该辅助函数

//list.vue
methods: {
	handleCityClick(){
		this.changeCity1(city)
		this.$router.push('/')
	},
	...mapMutations(['changeCity1'])  //这里相当于在methods中定义了一个名为changeCity1的函数

getters

作用有点类似于组件中的计算属性,对state中的数据进行计算

//index.js
export default new Vuex.store({
	state: state,
	mutations: mutations,
	getters: {
		doubleCity(state){
			return state.city + ' ' + state.city
		}
	}
})

使用的时候和mapState一样,在computed计算属性中使用

//header.vue
import { mapState, mapGetters } from 'vuex'

computed: {
	...mapState(['city']),
	...mapGetters(['doubleCity'])
}
<div class="button">{{this.doubleCity}}</div>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值