我创建了vue mixin函数,该函数返回项目的基本URL。我之所以需要这种混合,是因为在开发阶段,该值将来自配置文件,而在生产阶段,其值将来自全局变量window
。
可以从任何backEndHost
文件访问.vue
,但不能通过vuex操作访问。
Vue.mixin({
data: () => ({
get backEndHost() {
// ...
return (isDev) devAddr : prodAddr
}
})
})
const actions = {
getChallengesData({ commit, state }, task) {
// ...
axios.get(this.backEndHost() + url).catch((thrown) => {
swal('Error!', thrown.message, 'error')
}).then((res) => {
// ...
})
}
}
axios.get(this.backEndHost() + url)
触发了错误,表明this.backEndHost
未定义。
[Vue警告]:挂接的钩子中出现错误:“ TypeError:this.backEndHost不是函数”
任何想法如何解决此错误?还是有任何变通办法可以达到相同的结果?
答案 0 :(得分:1)
我最终将backEndHost
放入实用程序帮助程序(感谢@ittus)。由于我仍然需要backEndHost
在所有组件上都可用,因此我也将其放入mixin。
export function backEndHost() {
return (isDev) devAddr : prodAddr
}
import { backEndHost } from '@/utility/helper'
Vue.mixin({
data: () => ({
backEndHost
})
})
import { backEndHost } from '@/utility/helper'
const actions = {
getChallengesData({ commit, state }, task) {
// ...
axios.get(backEndHost() + url).catch((thrown) => {
swal('Error!', thrown.message, 'error')
}).then((res) => {
// ...
})
}
}