【问题标题】:node vue require library for use in componentnode vue 需要在组件中使用的库
【发布时间】:2017-01-04 18:38:08
【问题描述】:

我对使用 vue.js 和使用 NPM 的需要库的组件有了新的认识。

到目前为止,我使用 gulp Vueify 将我的核心代码与 .vue 文件一起编译成一个 bundle.js 文件。它适用于我的组件,但是当添加像 Axios 这样的东西时,它找不到库。

所以我做了NPM install axios --save-dev,这让我得到了图书馆。

然后是我的 vueCore.js 文件

var $               = require("jquery")
var Vue             = require('vue')
var axios           = require('axios')
var contentList     = require('./components/content-list.vue')
var heroHeader      = require('./components/hero-header.vue')

new Vue({
    el: '#page',
    components: {
        'dashboard-view': dashboard,    
        'content-list': contentList,
        'hero-header': heroHeader
    }
})

然后当我尝试在 dashboard 组件中使用 axios 时

mounted:  function() {

            axios.get('/custom_api/api_home_get.php?', {
                params: {
                  ID: i4
                }
              })
              .then(function (response) {
                this.last = response;
                console.log(response);
              })
              .catch(function (error) {
                console.log(error);
              });
}

然后我得到所有组件元素,错误为Uncaught ReferenceError: axios is not defined

【问题讨论】:

    标签: node.js vue.js


    【解决方案1】:

    你必须在你想使用的每个组件中 require('axios')。

    但我更喜欢的方式是使用 axios 设置 Vue.prototype.$http。 所以,在声明你的 Vue 应用之前,你要声明

    Vue.prototype.$http = axios
    

    那么 axios 将在您的任何组件中可用,而无需导入它。

    mounted: function() {
        this.$http.get('/whatever').then(whatever)
        ...
    }
    

    来源:vue-resource retirement

    【讨论】:

    • 那行得通。有没有办法只做一次,因为它只会在很多组件中使用?
    • 你可以设置'prototype'来包含你想要的任何东西,所以你的所有组件都会继承它。在我的研究项目中,我的原型中有 axios 和snackbar.js。
    猜你喜欢
    • 2021-04-27
    • 2021-07-31
    • 1970-01-01
    • 2020-06-12
    • 2018-10-14
    • 1970-01-01
    • 1970-01-01
    • 2018-10-04
    • 1970-01-01
    相关资源
    最近更新 更多