Antonio Morales
Antonio Morales

Reputation: 1074

Import into a vue.js component

I'm trying to import a library of the Vuelidate plugin into my newsletter.vue.js component.

But this import returns an error: Uncaught SyntaxError: Unexpected identifier

How can I import this into my vue.js component?

First to all, I´m using webpack and call first 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.

Like this example.

The problem is that I can't do an import inside my component vue, it always gives me error.

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)
        }
      }
    },

});

Upvotes: 5

Views: 1958

Answers (5)

hayreenfly
hayreenfly

Reputation: 91

Are you using vscode and 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.

 {
  "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. Does not have anything to do with vuelidate.

After you create your jsconfig and save it...restart vscode.

Upvotes: 0

codejockie
codejockie

Reputation: 10844

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:

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:

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.

Update: From the Bootstrap example link you provided, it is possible an older version of vuelidate.

Vuelidate does not provide a default export hence this import style import validators from 'vuelidate/lib/validators' doesn't work. Using named imports on the other hand works just fine.

Upvotes: 1

Nikola Kirincic
Nikola Kirincic

Reputation: 3757

First off, check in your node_modules if you have installed vuelidate at all:

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)
},

Upvotes: 0

vahdet
vahdet

Reputation: 6729

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)
        }
      }
    },

});

Upvotes: 0

SrAxi
SrAxi

Reputation: 20005

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'

Upvotes: 0

Related Questions