简体   繁体   English

导入一个 vue.js 组件

[英]Import into a vue.js component

I'm trying to import a library of the Vuelidate plugin into my newsletter.vue.js component.我正在尝试将Vuelidate插件库导入我的newsletter.vue.js组件。

But this import returns an error: Uncaught SyntaxError: Unexpected identifier但是这个导入返回一个错误: Uncaught SyntaxError: Unexpected identifier

How can I import this into my vue.js component?如何将其导入到我的 vue.js 组件中?

First to all, I´m using webpack and call first Vuelidate :首先,我正在使用 webpack 并首先调用 Vuelidate

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');


window.Vue = require('vue');

import BootstrapVue from 'bootstrap-vue'
import Vuelidate from 'vuelidate'

Vue.use(BootstrapVue)
Vue.use(Vuelidate)

/**
 * The following block of code may be used to automatically register your
 * Vue components. It will recursively scan this directory for the Vue
 * components and automatically register them with their "basename".
 *
 * Eg. ./components/ExampleComponent.vue -> <example-component></example-component>
 */

// const files = require.context('./', true, /\.vue$/i)
// files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default))

//Vue.component('example-component', require('./components/ExampleComponent.vue').default);

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

const app = new Vue({
});

window.onload = function(){
    app.$mount('#app');
}

Then I see that I have to import 'vuelidate/lib/validators' into the component in order to use it.然后我看到我必须将 'vuelidate/lib/validators' 导入到组件中才能使用它。

Like this example .这个例子

The problem is that I can't do an import inside my component vue, it always gives me error.问题是我无法在我的组件 vue 中进行导入,它总是给我错误。

This is the code of my component:这是我的组件的代码:

import validators from 'vuelidate/lib/validators';//this return me error

Vue.component('newsletter', {

    template :  '<div>\
      <b-form @submit="onSubmit">\
        \
          \
        <b-form-group id="exampleInputGroup2" label="Food" label-for="exampleInput2">\
          <b-form-select\
            id="exampleInput2"\
            :options="foods"\
            :state="$v.form.food.$dirty ? !$v.name.$error : null"\
            v-model="form.food"\
          />\
  \
          <b-form-invalid-feedback id="input2LiveFeedback">\
            This is a required field\
          </b-form-invalid-feedback>\
        </b-form-group>\
  \
        <b-button type="submit" variant="primary" :disabled="$v.form.$invalid">Submit</b-button>\
      </b-form>\
    </div>',

    props : ['route_post'],

    data: function()
    {
        return {
            foods: ['apple', 'orange'],
            form: {}
          }
    },  

    validations: {
      form: {
        name: {
          required: validators.required,
          minLength: validators.minLength(3)
        }
      }
    },

});

The error you got is as a result of not correctly importing what you want to use.您得到的错误是由于没有正确导入您想要使用的内容。 There are several ways to import this library.有几种方法可以导入这个库。

Import and use globally:全局导入和使用:

import Vue from 'vue'
import Vuelidate from 'vuelidate'
Vue.use(Vuelidate)

Alternatively, import a mixin directly to components:或者,将 mixin 直接导入到组件中:

import { validationMixin } from 'vuelidate'

var Component = Vue.extend({
  mixins: [validationMixin],
  validations: { ... }
})

Or或者

import { required, maxLength } from 'vuelidate/lib/validators'

Or import them individually to reduce import size:或者单独导入它们以减少导入大小:

import required from 'vuelidate/lib/validators/required'
import maxLength from 'vuelidate/lib/validators/maxLength'

You could also use require :您还可以使用require

const { required, minLength } = require('vuelidate/lib/validators')

For your use case, validators doesn't exist in 'vuelidate/lib/validators' as it is not a property/member.对于你的使用情况, validators不存在'vuelidate/lib/validators' ,因为它不是一个属性/成员。

Update: From the Bootstrap example link you provided, it is possible an older version of vuelidate.更新:根据您提供的 Bootstrap 示例链接,可能是 vuelidate 的旧版本。

Vuelidate does not provide a default export hence this import style import validators from 'vuelidate/lib/validators' doesn't work. Vuelidate 不提供默认导出,因此import validators from 'vuelidate/lib/validators'这种导入样式import validators from 'vuelidate/lib/validators'不起作用。 Using named imports on the other hand works just fine.另一方面,使用命名导入效果很好。

You first have to add it to your app like this:您首先必须像这样将它添加到您的应用程序中:

import Vue from 'vue'
import Vuelidate from 'vuelidate'
Vue.use(Vuelidate)

Then, you can use it by destructuring, like this:然后,您可以通过解构来使用它,如下所示:

import { validators } from 'vuelidate'

ES6 ES6

Use named import and change the validations section as follows:使用命名导入并按如下方式更改验证部分:

import { validators, minLength } from 'vuelidate/lib/validators';

Vue.component('newsletter', {

    template :  `<div>
      <b-form @submit="onSubmit">
        <b-form-group id="exampleInputGroup2" label="Food" label-for="exampleInput2">
          <b-form-select
            id="exampleInput2"
            :options="foods"
            :state="$v.form.food.$dirty ? !$v.name.$error : null"
            v-model="form.food"
          />
          <b-form-invalid-feedback id="input2LiveFeedback">
            This is a required field
          </b-form-invalid-feedback>
        </b-form-group>
        <b-button type="submit" variant="primary" :disabled="$v.form.$invalid">Submit</b-button>
      </b-form>
    </div>`,

    props : ['route_post'],

    data: function()
    {
        return {
            foods: ['apple', 'orange'],
            form: {}
          }
    },  

    validations: {
      form: {
        name: {
          required,
          minLength: minLength(3)
        }
      }
    },

});

First off, check in your node_modules if you have installed vuelidate at all:首先,如果您已经安装了vuelidate ,请检查您的 node_modules:

npm install vuelidate --save

validators doesn't have exports default, you need to use destructuring to import each validation separately:验证器没有默认导出,您需要使用解构来分别导入每个验证:

import { required, minLength } from 'vuelidate/lib/validators'; 

Vue.component('newsletter', {

... 
validations: {
name: {
  required,
  minLength: minLength(3)
},

Are you using vscode and vetur?你在使用 vscode 和 vetur 吗? Not sure if we encountered the same problem.不确定我们是否遇到了同样的问题。 But how I solved my problem was adding a jsconfig.json file on my root project folder and putting this code inside.但是我如何解决我的问题是在我的根项目文件夹中添加一个 jsconfig.json 文件并将此代码放入其中。

 {
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    // This is the line you want to add
    "allowSyntheticDefaultImports": true
  },
  "exclude": ["node_modules", "**/node_modules/*"]
 }

I think the import problem was due to vscode and intellisense.我认为导入问题是由于 vscode 和智能感知。 Does not have anything to do with vuelidate.与 vuelidate 没有任何关系。

After you create your jsconfig and save it...restart vscode.创建 jsconfig 并保存后...重新启动 vscode。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM