【问题标题】:Storage not working properly in vuex axios response存储在 vuex axios 响应中无法正常工作
【发布时间】:2019-04-03 10:11:45
【问题描述】:

每当我使用 axios 响应将数据发送到 vuex 存储时,例如。

** Sidebar.vue **
  created(){
    this.getRoles();
  },
  methods: {
    getRoles(){
      var _this = this
      var roles = null
      this.$http.get('/api/userroles/userroles').then(function(response){
        // Passing data to vuex within response
        _this.$store.dispatch('setUserRoles', response.data.data)
      }
    }
    check_role(){

    }
  }

当我像 console.log(this.$store.state.userStore.roles) 这样在侧边栏中进行控制台时它具有价值,但是当我在仪表板中控制台时它返回 null 并且当我看到 vuex chrome 扩展它包含值(下图),但在仪表板中它返回 null

eg in dashboard 

** dashboard.vue **
created(){
  console.log(this.$store.state.userStore.roles)
  // null
},

现在,当我在 axios 响应之外分派到 vuex 时,它可以完美运行并在仪表板中提供价值,但它会抛出错误,例如 Error: [vuex] Do not mutate vuex store state outside mutation handlers。例如。

created(){
  this.getRoles();
},
methods: {
  getRoles(){
    var _this = this
    var roles = null
    this.$http.get('/api/userroles/userroles').then(function(response){
      _this.roles_data = response.data.data
    }
    _this.$store.dispatch('setUserRoles', _this.roles_data)
  }
}

例如在仪表板中,如果我在 axios 之外使用调度,它会提供价值

** dashboard.vue **
created(){
  console.log(this.$store.state.userStore.roles)
  // (25) [{…}, {…}, {…}, __ob__: Observer]
},

我错过了什么吗???

【问题讨论】:

    标签: javascript vue.js vuex


    【解决方案1】:

    试试这个:

    created () {
      this.getRoles()
    },
    
    methods: {
      getRoles () {
        this.$http
          .get('/api/userroles/userroles')
          .then(({data: {data}}) => {
            this.$store.dispatch('setUserRoles', data)
          })
      }
    }
    

    并且不要尝试在 created 方法中控制台角色。因为它不能工作,axios是异步的,你会在数据到达之前控制台状态。如果,也可以在 axios 回调中对其进行控制台:

    created () {
      this.getRoles()
    },
    
    methods: {
      getRoles () {
        this.$http
          .get('/api/userroles/userroles')
          .then(({data: {data}}) => {
            this.$store.dispatch('setUserRoles', data)
            // here, not in created method
            console.log(this.$store.state.userStore.roles)
          })
      }
    }
    

    【讨论】:

    • 我仍然在dashboard.vue中得到空值
    • 并且axios回调中的console.log按预期工作?
    • 是的。它显示了结果。当我在 vmodel 中传递响应然后将 vmodel 分派到 vuex 时,它不起作用。但是当我在 axios 外部传入一个变量时,它可以正常工作,但会抛出类似 "Error: [vuex] Do not mutate vuex store state outside mutation handlers." 之类的错误。
    • 然后,一切都按预期进行。您无法在 created 方法中控制 dashboard.vue 中的这些值。
    • 那么我怎样才能在仪表板中获得角色访问权限。我不想每次页面加载时都触发 api。
    【解决方案2】:

    您正在尝试在调用 api 之前控制 store.state.userStore.roles。避免在 created() 中访问存储值

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-03
      • 2021-08-31
      • 1970-01-01
      相关资源
      最近更新 更多