4

I used bootstrap-toggle in Vuejs. When run the project I got an error "bootstrapToggle is not a function"

This is my VueJs Components looks like

<template>
  <input type='checkbox' id="toggle-checked" v-model="active">
</template>
<script type="text/babel">
  import $ from 'jquery'
  require('bootstrap-toggle')

  export default {
    data () {
      return {
        active: 1
      }
    },
    mounted: function () {
      $('#toggle-checked').bootstrapToggle()
    }
  }
</script>

2 Answers 2

3

One of webpack benefits is that you can make module available in all of your files. In Vue.js we talk in components. So what you did is that you use jQuery module in you component and it will be available only in that component. To make it global add to your webpack config file:

webpack.base.conf.js

var webpack = require("webpack")

module.exports = {
  plugins : [
        new webpack.ProvidePlugin({
            $ : "jquery",
            jQuery : "jquery"
        })
  ],
};

simple configuration webpack config file. Now jQuery will be available in all of your components, and now component looks cleaner:

Vue component

<template>
   <input type='checkbox' id="toggle-checked" v-model="active">
</template>
<script type="text/babel">

      require('bootstrap-toggle')

      export default {
        data () {
          return {
            active: 1
          }
        },
        mounted: function () {
          $('#toggle-checked').bootstrapToggle()
        }
      }
</script>

This approach is good for a complex web apps with many assets such as CSS, images and other loaders, and Webpack will give you great benefits. But if is your app small Webpack will be overhead.

Sign up to request clarification or add additional context in comments.

9 Comments

After edit webpack.base.conf.js file, I got $ not defined.
Did you install jquery via npm?
Add "window.jQuery": 'jquery' to your ProvidePlugin to look like this jsfiddle.net/re238zjx
Also did you include bootstrap-toggle.min.css in your index.html file -> <link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
And finally added inside nextTick this.$nextTick(function () { $('#toggle-checked').bootstrapToggle() });
|
0

Instead of using require for bootstrap-toggle, you can add following lines in your index.html, which should fix this.

<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.