简体   繁体   中英

Understanding ES6 Modules import/export

I'm starting learn ES6 modules and import / export syntax and I want that my modules are executed only where they are needed.

I created two simple modules that connect to a <div> with a particular class or id to run.

For example:

// product.js

import Vue from 'vue/dist/vue';

export default function() {

  var app = new Vue({
    el: '#c-product',
    data: {
      counter: 0,
    },
    methods: {
      addToCart: function() {
        this.counter++;
      },
      removeFromCart: function() {
        this.counter--;
      }
    }
  });

}

Then I have the other module for a carousel:

// carousel.js

import Glide from '@glidejs/glide';

export default function() {

  new Glide('.glide', {
    type: 'carousel',
    startAt: 0,
    perView: 3,
    breakpoints: {
      800: {
        perView: 2
      }
    }
  }).mount();

};

Then I bundle everything with Gulp + Browserify in order to have a main.js file where I import and execute the modules:

// main.js
import Product from './product';
import Carousel from './carousel';

Product();
Carousel();

Now I have my main.js file and I'm ready to insert it into the .html pages, but I have errors in console depending on whether those divs exist in page or not.

Example: if in product.html page there are no carousels, I have errors in console regarding missing the <div> with the carousel class.

Hope to be clear.

Can you help me understand?

Here the example on product page

You can solve it with a bit of defensive coding. Each of your modules depend on a certain DOM node being present, so you should query for the element before instantiating the module. Like:

// product.js

import Vue from 'vue/dist/vue';

export default function() {
  var vueRoot = document.getElementById('c-product')
  if (!vueRoot) return;  // element does not exist, so we return before instantiating

  var app = new Vue({
    el: '#c-product',
    data: {
      counter: 0,
    },
    methods: {
      addToCart: function() {
        this.counter++;
      },
      removeFromCart: function() {
        this.counter--;
      }
    }
  });

}

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