【问题标题】:Using 3rd party jquery library with vueJS and webpack使用带有 vueJS 和 webpack 的 3rd 方 jquery 库
【发布时间】:2017-01-06 10:11:06
【问题描述】:

我在 Vuejs 中使用了bootstrap-toggle。运行项目时出现错误“bootstrapToggle 不是函数”

这是我的 VueJs 组件的样子

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

【问题讨论】:

    标签: jquery twitter-bootstrap twitter-bootstrap-3 vuejs2


    【解决方案1】:

    webpack 的一个好处是你可以在你的所有文件中使用模块。在 Vue.js 中,我们谈论组件。所以你所做的就是在你的组件中使用 jQuery 模块,它只在那个组件中可用。要使其全局添加到您的 webpack 配置文件:

    webpack.base.conf.js

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

    简单配置webpack config file。现在 jQuery 将在你的所有组件中可用,现在组件看起来更干净了:

    Vue 组件

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

    这种方法适用于具有许多资产(如 CSS、图像和其他加载器)的复杂 Web 应用程序,Webpack 将为您带来巨大的好处。但是如果你的应用是小 Webpack 将会是开销。

    【讨论】:

    • 编辑webpack.base.conf.js文件后,我得到$未定义。
    • 你是通过 npm 安装 jquery 的吗?
    • 将 "window.jQuery": 'jquery' 添加到您的 ProvidePlugin 中,使其看起来像这样 jsfiddle.net/re238zjx
    • 你是否也在你的 index.html 文件中包含了 bootstrap-toggle.min.css -> &lt;link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet"&gt;
    • 最后在nextTick里面添加了this.$nextTick(function () { $('#toggle-checked').bootstrapToggle() });
    【解决方案2】:

    您可以在index.html 中添加以下行,而不是使用require 代替bootstrap-toggle,这应该可以解决此问题。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-01
      • 2016-06-08
      • 2020-04-08
      • 2018-03-27
      • 1970-01-01
      • 2017-04-10
      • 2017-02-24
      • 1970-01-01
      相关资源
      最近更新 更多