为什么我得到Vue并没有定义为错误:
export default {
state: {
projects: {
loading: true,
failed: false,
lookups: [],
selectedId: 0
}
},
mutations: {
loadingProjectLookups (state, payload) {
state.projects.loading = true;
state.projects.failed = false;
}
},
actions: {
loadProjectLookups (context) {
return new Promise((resolve) => {
// VUE NOT DEFINED HERE:
Vue.http.get('https://my-domain.com/api/projects').then((response) => {
context.commit('updateProjectLookups', response.data);
resolve();
},
response => {
context.commit('failedProjectLookups');
resolve();
});
});
}
}
}
这是我的Vue配置:
'use strict';
import Vue from 'vue';
import Vuex from 'vuex';
var VueResource = require('vue-resource');
/* plugins */
Vue.use(Vuex);
Vue.use(VueResource);
/* stores */
import importPageStore from './apps/import/import-page-store';
/* risk notification import */
import ImportApp from './apps/import/import-app.vue';
if (document.querySelector("#import-app")) {
var store = new Vuex.Store(importPageStore);
new Vue({
el: '#import-app',
store,
render: h => h(ImportApp)
});
}
我的理解是Vue是全局定义的,我看不到为什么未定义它。如果我将其添加import Vue from 'vue'
到商店中,则会收到一条消息,提示未定义http。因此,我需要弄清楚为什么Vue似乎无法在全球范围内使用,因为我不必这样做。
我正在使用webpack构建我的vue组件。我还有其他使用此方法呈现的页面,它们工作得很好。但这不是吗?老实说,我为为什么看不到任何差异而感到困惑。页面呈现并工作。我可以看到Vue正在运行。怎么不确定呢?
在组件中,可以使用this.$http
,但是在商店中,Vue
每次都需要导入。
您可以做的是创建一个service
文件夹,然后将Vue导入其中。然后,只需在商店文件中引用您的服务即可。
这里有一个例子https://github.com/vuejs/vuex/issues/85
这表明是这样的:
/services/auth.js
import Vue from 'vue'
export default {
authenticate(request) {
return Vue.http.post('auth/authenticate', request)
.then((response) => Promise.resolve(response.data))
.catch((error) => Promise.reject(error));
},
// other methods
}
在您的商店文件中:
import { AUTHENTICATE, AUTHENTICATE_FAILURE } from '../mutation-types'
import authService from '../../services/auth'
export const authenticate = (store, request) => {
return authService.authenticate(request)
.then((response) => store.dispatch(AUTHENTICATE, response))
.catch((error) => store.dispatch(AUTHENTICATE_FAILURE, error));
}
// other actions
这就是VueResource扩展Vue
原型的方式。
Object.defineProperties(Vue.prototype, {
// [...]
$http: {
get() {
return options(Vue.http, this, this.$options.http);
}
},
// [...]
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句