一.获取vuex中的数据
1-1.如何获取vuex中的数据
$store.data.city
//1.新建vue文件时,选中vuex//2.在src/router/index.js中添加数据export default new Vuex.Store({state: {city:"武汉"},...})//3.在主页面使用vue中的数据export default {name: 'home',mounted(){console.log(this.$store.state.city)},computed:{city(){ //可以通过计算属性拿到cityreturn this.$store.state.city}}}//4.使用<router-link to="/detail" tag="p">{{city}}</router-link>//或者 <router-link>{{this.$store.state.city}}</router-link>
1-2this.$store.dispatch向vuex派发一个事件—actions,同时传递一个参数—city
//跳转的对应detail页面中,再从detail页面中跳到首页<router-link to="/films/nowPlaying" tag="button" v-for="item of cities" :key="item"@click.native="handleClick(item)">{{item}}</router-link>export default {name:"Detail",data(){return{cities:["上海","北京","深圳","广州"]}},methods:{handleClick(city){/* this.$store.dispatch 向vuex派发一个事件,同时传递一个参数 */this.$store.dispatch("changeCity",city)}}
二.组件@click事件
@click.native //给组件事件必须加上.native修饰符
三.vuex的工作

//1.通过this.$store.dispatch()向vuex中的actions派发一个事件同时传递一个参数methods:{handleClick(city){/* this.$store.dispatch 向vuex派发一个事件,同时传递一个参数 */this.$store.dispatch("changeCity",city)}}//2.vuex-actions中接收dispatch派发过来的事件和参数export default new Vuex.Store({...actions: {changeCity(ctx,city){/* ctx表示上下文 this.$storecity是自定义事件传递过来的参数 *///3.在actions中使用commit方法向mutations提交一个事件,同时传递一个参数ctx.commit("toggleCity",city) //toggleCity:自定义一个事件名}},})//4.在mutations中接收actions派发过来的事件和参数,并修改参数export default new Vuex.Store({state: {city:"武汉"},mutations: {toggleCity(state,city){state.city=city}},actions: {changeCity(ctx,city){ctx.commit("toggleCity",city)}},})
四.数据持久化
//1.设置缓存export default new Vuex.Store({...actions: {changeCity(ctx,city){ctx.commit("toggleCity",city)localStorage.setItem("city",city)}},})//2.获取缓存,有缓存就取缓存,没有缓存就设置缓存function getCity(){let defaultCity="武汉";if(localStorage.getItem("city")){defaultCity=localStorage.getItem("city")}return defaultCity}//3.使用export default new Vuex.Store({state: {city:getCity()},...})
