我在 Vuejs 中使用了 bootstrap-toggle。运行项目时,出现错误"bootstrap切换不是函数"
这是我的 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>
webpack 的好处之一是您可以在所有文件中提供模块。在 Vue 中.js我们在组件中讨论。所以你所做的是你在组件中使用jQuery模块,它只能在该组件中使用。要使其全局添加到您的 webpack 配置文件中:
webpack.base.conf.js
var webpack = require("webpack")
module.exports = {
plugins : [
new webpack.ProvidePlugin({
$ : "jquery",
jQuery : "jquery"
})
],
};
简单的配置 webpack 配置文件。现在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将产生开销。
而不是使用 require
表示bootstrap-toggle
,您可以在index.html
中添加以下行,这应该可以解决此问题。
<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>