gpt4 book ai didi

javascript - 无法从 2.0RC 中的组件访问 vue-resource 的 $http 方法

转载 作者:行者123 更新时间:2023-11-28 05:40:26 25 4
gpt4 key购买 nike

我在 2.0RC 的 .vue 组件中使用 vue-resource 时遇到问题。它在 1.x 中工作正常,但现在从组件方法中访问 this 时,$http 方法似乎丢失了。

我正在使用 webpack,我的 app.es6 文件如下所示:

import Vue from 'vue/dist/vue.js'
import VueRouter from 'vue-router'
import VueResource from 'vue-resource'
import Login from './Login.vue'

Vue.use(VueResource);
Vue.use(VueRouter);

const router = new VueRouter({
mode: 'history',
base: __dirname,
routes: [
{ path: '/login', component: Login }
]
})

const App = new Vue({
router: router,
el: "#vue-app",
template: '<div><router-view></router-view></div>',
created: function(){
console.log('data this: ', this.$http()) //this $http.get() works
}

})

我的 Login.vue 看起来像:

<template>
<div>
<h2>Log In</h2>
<button class="btn btn-primary" @click="submit()">Access</button>
</div>
</template>
<script type="text/ecmascript-6">
export default {
methods: {
submit: function () {
console.log('Login this.$http()', this.$http.get) //this $http.get() does not work
}
}
}
</script>

一些理论是:

  1. 2.0 以某种方式破坏了一些东西,但 vue-resource 文档尚未更新。
  2. 这与版本 1 中的 Vue.extend(...) 和 Vue.start(...) 更改为 new Vue() 我现在使用的语法。
  3. 我需要使用新的 vue-router 语法做一些不同的事情。

感谢您的帮助。

最佳答案

我得到了 answer over on the Vue Help forum 。出现这个问题是因为我使用的是 Vue 的独立版本,但没有在 Webpack 中完全别名化它,因此 Webpack 加载了两个不同的版本。

用户 LinusBorg 回答:

You require the standalone build, but webpack is also loading the runtime-only build, so you end up with two versions of Vue in your project - one has vue-resource, the other doesn't.

If you want to keep the standalone build, you have to add an alias to your webpack config: vue: 'vue/dist/vue'

以防万一其他人也遇到这个问题并且像我一样对 webpack 感到困惑,稍微更明确一点:

Webpack 正在加载两个不同版本的 vue.js,一种来 self 的文件内 import 语句,另一种来自 webpack *.vue 模块加载器。我修复它的确切方法是将以下内容添加到我的 webpack-config.js 中:

resolve: {
alias: {vue: 'vue/dist/vue.js'}
},

在我的 app.es6 文件中,我还必须将 import Vue from 'vue/dist/vue.js' 改回 import Vue from 'vue'

关于javascript - 无法从 2.0RC 中的组件访问 vue-resource 的 $http 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38959538/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com