66. Vue 结合webpack使用jquery以及boostrap

412 阅读1分钟

需求

有时候在 Vue 框架开发的时候,还是存在需要使用 jquery 以及 boostrap 的场景的,这个时候就需要安装 Jquery 以及 boostrap 了。

安装 jquery 以及 popper

使用 npm 安装 jquery

cnpm i jquery --save
或者
cnpm i jquery -S

使用 npm 安装 popper

cnpm install popper.js@^1.16.1 --save
# 这个版本号其实是在安装 cnpm install bootstrap --save 之后就会提醒要安装哪个版本的依赖。

webpack.config.js 中配置导入 jquery 以及 popper

image-20200825143157287

// webpack插件
const webpack=require('webpack');

module.exports = {
    ...
        plugins: [ // 配置插件的节点
            ..
            new webpack.ProvidePlugin({ // 配置jquery
                $: "jquery",
                jQuery: "jquery",
                "windows.jQuery": "jquery", // 添加plugins
                Popper: ['popper.js', 'default'], // 添加Popper
            }),
    ],
}

安装 Bootstrap4

使用 npm 安装 boostrap

cnpm install bootstrap --save

在 main.js 导入 boostrap

// 导入Boostrap
import 'bootstrap/dist/js/bootstrap.min.js'
import 'bootstrap/dist/css/bootstrap.min.css'

image-20200825143244682

在组件中尝试使用一个 modal

image-20200825143324607

        <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
            Launch demo modal
        </button>
        <button class="btn btn-success" @click="openModal">
            通过js打开
        </button>

        <!-- Modal -->
        <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <!-- 增加类modal-dialog-centered 就可以设置模态窗口垂直居中-->
            <div class="modal-dialog modal-dialog-centered" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel">信息</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        请确认是否删除!
                    </div>
                    <div class="modal-footer">
                        <!--自定义按钮的id进行监听即可-->
                        <button type="button" class="btn btn-secondary" data-dismiss="modal" id="modal-btn-close">关闭</button>
                        <button type="button" class="btn btn-primary"  data-dismiss="modal" id="modal-btn-save" >确认删除</button>
                    </div>
                </div>
            </div>
        </div>

image-20200825143411046

           openModal(){
                $('#exampleModal').modal('show');
            }

页面效果如下:

image-20200825143447946

可以看到已经可以成功使用了。

更多精彩原创Devops文章,快来关注我的公众号:【Devops社群】 吧