E
E
Erik21212018-11-13 12:45:50
JavaScript
Erik2121, 2018-11-13 12:45:50

How to access jQuery in Nuxt.js?

Hello, I can’t understand where I’m wrong, please tell me)

Error: jQuery requires a window with a document

FG4RSblmYfQ.jpg

In nuxt.config.js :

const webpack = require('webpack')

module.exports = {

  /*
  ** Headers of the page
  */
  head: {
    title: 'Nes 1', 
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: 'Nuxt.js project' }
    ],
    script: [
      { src: 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js' },
      { src: 'https://cdnjs.cloudflare.com/ajax/libs/air-datepicker/2.2.3/js/datepicker.min.js' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
      { rel: 'stylesheet', href: 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css' },
      { rel: 'stylesheet', href: 'https://cdnjs.cloudflare.com/ajax/libs/air-datepicker/2.2.3/css/datepicker.min.css' }
    ],
  },

  /*
  ** Customize the progress bar color
  */
  loading: { color: '#3B8070' },
  /*
  ** Build configuration
  */
  build: {
    /*
    ** Run ESLint on save
    */    
    plugins: [
      new webpack.ProvidePlugin({
         $: 'jquery',
          jquery: 'jquery',
          'window.jQuery': 'jquery',
          jQuery: 'jquery'
      })
    ],
    extend (config, { isDev, isClient }) {
      if (isDev && isClient) {
        config.module.rules.push({
          enforce: 'pre',
          test: /\.(js|vue)$/,
          exclude: /(node_modules)/
        })
      }
    }
  }
}


In index.vue :
<script>
import IndexCart from '~/components/IndexCart'

export default {	
  components: {
    IndexCart
  },
  data() {
  return {
      message: 'Message',
      cardState: true,
      list: false
    }
  },
  methods: {
  	select() {
  		console.log($);
  	}
  },
  computed: {
  	
  },
  created() {
    console.log ( $('#calendar').html() );
  }
}

</script>


Here is the error that appears in the console when I try to print an object using the .html() method

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly Mosin, 2018-11-13
@Erik2121

1. Call jquery methods in the mounted hook, this is similar:

$(document).ready(function() {
    // all custom jQuery will go here
});

the 'created' paged hook in Nuxt is called on the server side, and window.
2. It may also be useful to import jQuery into a separate plugin in the 'plugins' directory and include it in nuxt.config.js with the flag ssr: false

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question