求助:使用vue 路由钩子函数存储数据?

图片描述

1,跳转成功,从【购物车】传给【确认订单】页面的数据

图片描述

2,成功传送

图片描述

3,当【确认订单】页面点击选择【选择地址】页面,返回时候数据丢失。

4,问:能否使用vue 路由钩子函数实现存储数据的目的?怎么存储?(不使用返回再次发送请求的方法~)

阅读 4k
2 个回答

vuex
入口文件用vuex建个全局info

const store = new Vuex.Store({
  state:{
    info:
  }
  ...
})

在路由钩子中使用this.$store.state.info修改及取值即可
beforeRouteEnter的时候,不能使用this,官方文档提供了vm.XXX取值

beforeRouteEnter (to, from, next) {
  next(vm => {
    // 通过 `vm` 访问组件实例
    vm.$store.state.info= xxxxx;
  })
},

vuex比较好控制
或者你也可以用localstorage
vuex 在入口文件中初始化所有需要的数据:

Vue.use(Vuex);
// Vue.config.productionTip = false
/* eslint-disable no-new */
//Vuex默认数据
const store=new Vuex.Store({
  state:{
    defUrl: 'https://free-api.heweather.com/v5',
    key: 'd88adc07ebae43c481b1462ad4a5c086',
    forecast: null,
    now: null,
    hourly: null,
    suggestion: null,
    basic: null,
    city: null
  },
  mutations:{},
  getters:{},
  actions:{}
})

在需要使用数据的地方
使用 import {mapState} from 'vuex'导入数据

  computed:{
    ...mapState([
//        用vuex导入state变量
      'defUrl', 'key', 'forecast', 'now', 'hourly', 'suggestion', 'basic', 'city'
    ])
  },
 this.$store.state['forecast']=response.data.HeWeather5[0].daily_forecast // 7-10天预报
      this.$store.state['now'] = response.data.HeWeather5[0].now // 实况天气
      this.$store.state['hourly'] = response.data.HeWeather5[0].hourly_forecast // 每小时预报(逐小时预报),最长10天
      this.$store.state['suggestion'] = response.data.HeWeather5[0].suggestion // 生活指数
      this.$store.state['basic'] = response.data.HeWeather5[0].basic
      this.$store.state['city'] = response.data.HeWeather5[0].aqi

给数据赋值

或者用本地存储:

 localStorage.setItem('skinColor', skinColor);//存储到localStorage
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题