简体   繁体   中英

VueJS 2 server-side rendering with jQuery plugin

I'm trying to convert an old landing page that has a few jQuery plugins to a Vue app. The reason is, that the landing page is being extended and will become a web app.

Using https://github.com/vuejs/vue-hackernews-2.0/ as a template. Main reason is that it does server side rendering.

Problem is the error:

ReferenceError: window is not defined
    at Object.<anonymous> (__vue_ssr_bundle__:3398:2408)
    at __webpack_require__ (__vue_ssr_bundle__:21:30)
    at Object.module.exports.Object.defineProperty.value (__vue_ssr_bundle__:1280:126)
    at __webpack_require__ (__vue_ssr_bundle__:21:30)
    at Object.<anonymous> (__vue_ssr_bundle__:2099:3)
    at __webpack_require__ (__vue_ssr_bundle__:21:30)
    at Object.<anonymous> (__vue_ssr_bundle__:1380:81)
    at __webpack_require__ (__vue_ssr_bundle__:21:30)
    at Object.module.exports.Object.defineProperty.value (__vue_ssr_bundle__:378:66)
    at __webpack_require__ (__vue_ssr_bundle__:21:30)

So far, I've found out that the problem is caused by window not being in Node. However, I do not know how to make it available or how I should inject jQuery after the page is server side rendered.

vue-hackernews-2.0 is almost unchanged. The main change I did was adding jQuery to webpack.client.config.js .

This is added to plugins (found another answer that it should make jQuery available when it's needed in the app):

new webpack.ProvidePlugin({
  $: 'jquery',
  jquery: 'jquery',
  'window.jQuery': 'jquery',
  jQuery: 'jquery'
})

And this is the LandingView.vue

<template>
  <div class="landing-page">
  </div>
</template>

<script>
  import owl from '../../public/assets/libs/owl.carousel.2.0.0-beta.2.4/owl.carousel.min.js'
  import $ from 'jquery';

  export default {
    name: 'landing-view',
    created () {
      console.log('hello world!');
    }
  }
</script>

It turns out I needed to inject my jQuery plugin on mounted event https://v2.vuejs.org/v2/api/?#mounted

It also says

This hook is not called during server-side rendering.

I just assigned the plugin to window and then I was able to initiate it.

<template>
  <div class="landing-page">
  </div>
</template>

<script>
  // import $ from 'jquery'; //no need to import it, as it's provided by webpack

  export default {
    name: 'landing-view',
    mounted() {
      // created() is only available in v1

      window.owl = require('../../public/assets/libs/owl.carousel.2.0.0-beta.2.4/owl.carousel.min.js');


      // the rest of my code
      $('.some-carousel').owlCarousel();

    }
  }
</script>

I am not sure if this is the proper way to solve this. I appreciate any comments on best practices!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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