如何在 vue-resource 中读取 store setters 值?

How in vue-resource read store setters value?

在我的 vue/cli 4/vuex / vue-resource 项目中,我使用来自后端 api 的护照从保护区读取数据,如 routes/api.php:

Route::group(['middleware' => 'auth:api',  'prefix' => 'adminarea', 'as' => 'adminarea.'], function ($router) {
    ...
    Route::get('dashboard', 'API\Admin\DashboardController@index');

我在

在 src/main.js 中我添加了方法 :

Vue.http.interceptors.push((request, next) => {   
/*
  console.log('request::')
  console.log(request)

  console.log('this::')
  console.log(this)

  console.log('Vue::')
  console.log(Vue)

  console.log('Vue.$store::')
  console.log(Vue.$store)

  console.log('Vue.$store.getters.token::')
  console.log(Vue.$store.getters.token)
*/

  request.headers.set('Authorization', 'Bearer XXX key')
  request.headers.set('Accept', 'application/json')
  next()
})

如果我手动填写不记名令牌,它对我有用,但我没有找到如何从商店读取它? 在我上面的代码中,我未能读取 $store.getters 值... 哪种方法有效?

更新块 #1: 如果在 src/main.js 我注释行:

import store from './store'

并添加行:

import store from './store.js';

然后在控制台中出现错误:

 ERROR  Failed to compile with 1 errors                                                                                                                                                                                           12:55:54 PM

This relative module was not found:

* ./store.js in ./src/main.js

但是

import store from './store'

我无法访问存储数据

谢谢!

尝试导入您的 Vuex 文件,而不是尝试通过 Vue 实例访问 $store

import store from './store.js';

Vue.http.interceptors.push((request, next) => {   
      request.headers.set('Authorization', `Bearer ${store.getters.token}`)
      request.headers.set('Accept', 'application/json')
      next()
})

我发现在登录时将令牌写入 localStorage 的决定

reading this value from ue.http.interceptors.push((request, next) => { 
  let token = localStorage.getItem('token')
  request.headers.set('Authorization', 'Bearer '+token)
  request.headers.set('Accept', 'application/json')
  next()
})

这对我有用!