@Erik2121

Как получить доступ к jQuery в Nuxt.js?

Привет, не могу понять где ошибаюсь подскажите пожалуйста)

Ошибка: jQuery requires a window with a document

FG4RSblmYfQ.jpg

В 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)/
        })
      }
    }
  }
}


В 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>


Вот ошибка появляется как в консоли пытаюсь распечатать объект методом .html()
  • Вопрос задан
  • 2886 просмотров
Решения вопроса 1
c_i_h
@c_i_h
Full-Stack PHP/JS
1. Вызывай методы jquery в хуке mounted, это аналогично:
$(document).ready(function() {
    // all custom jQuery will go here
});

хук 'created' paged компонент в Nuxt вызывается на стороне сервера, а там не существует window.
2. Так же возможно полезным будет вынести импорт jQuery в отдельный плагин в каталог 'plugins' и подключить его в nuxt.config.js с указанием флага ssr: false
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы