为什么为 vue-resource 设置 Vue.http 会被忽略?
我正在使用 Vue.js 2.3.3、Vue Resource 1.3.3、Vue Router 2.5.3,并尝试设置 Vue-Auth。但是,我不断收到控制台错误,提示
auth.js?b7de:487 Error (@websanova/vue-auth): vue-resource.1.x.js : 必须设置 Vue.http。
。我在 main.js 中设置了
Vue.http
,但是 vue-resource 由于某种原因没有选择它。
main.js:
import Vue from 'vue'
import Actions from 'actions'
import App from './App'
Vue.use(Actions, {
locales: ['en', 'zh', 'fr']
})
Vue.http.options.root = 'https://api.example.com'
new Vue({
render: h => h(App),
watch: {
lang: function (val) {
Vue.config.lang = val
}
}
}).$mount('#app')
actions/index.js
import VueResource from 'vue-resource'
import Router from 'actions/router'
import I18n from 'actions/i18n'
export default {
install (Vue, options) {
Vue.use(Router)
Vue.use(I18n, options.locales)
Vue.use(require('@websanova/vue-auth'), {
router: require('@websanova/vue-auth/drivers/router/vue-router.2.x'),
auth: require('@websanova/vue-auth/drivers/auth/bearer'),
http: require('@websanova/vue-auth/drivers/http/vue-resource.1.x')
})
}
}
如果我将
Vue.use(VueResource)
添加到
Vue.use(Router)
正下方的 action/index.js 中,我会收到一个新错误:
Error (@websanova/vue-auth): vue-router.2.x.js : 必须设置 Vue.router。
另一方面,如果我将
Vue.http.options.root = 'https://api.example.com'
移动到 import 语句正下方,我会收到另一个错误:
Uncaught TypeError: Cannot read property 'options' 未定义
您需要将“vue-resource”导入到您的 main.js 文件中以解决此错误:
import Vue from 'vue'
import VueResource from 'vue-resource';
import Actions from 'actions'
import App from './App'
Vue.use(Actions, {
locales: ['en', 'zh', 'fr']
})
Vue.use(VueResource)
Vue.http.options.root = 'https://api.example.com'
new Vue({
render: h => h(App),
watch: {
lang: function (val) {
Vue.config.lang = val
}
}
}).$mount('#app')
使用
axios
而不是
vue-resource
,这对我来说是一个有效的设置:
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueRouter)
Vue.use(VueAxios, axios)
Vue.router = new VueRouter({
// Your routes.
})
Vue.use(require('@websanova/vue-auth'), {
auth: require('@websanova/vue-auth/drivers/auth/bearer.js'),
http: require('@websanova/vue-auth/drivers/http/axios.1.x.js'),
router: require('@websanova/vue-auth/drivers/router/vue-router.2.x.js'),
})
App.router = Vue.router
new Vue(App).$mount('#app')
For more guidance you can refer to this great tutorial: https://codeburst.io/api-authentication-in-laravel-vue-spa-using-jwt-auth-d8251b3632e0