zl程序教程

您现在的位置是:首页 >  Javascript

当前栏目

取代Jquery,用Vue 构建Bootstrap 4 应用

2023-03-15 22:35:57 时间

尽管前端程序现在发展迅速,各种框架层出不穷,但是对广大非前端码农来说构建Web界面的最好的选择仍然还是Bootstrap 4。但是Bootstrap依赖于已经严重过时,被抛弃的jQuery组件,那么如何解决这个问题就迫在眉睫了。

Vue项目以其轻巧、高性能,易上手,双向数据绑定,组件化的特点,快速流行并广为使用,那么有没有可能将Bootstrap的依赖改为Vue呢?答案是肯定的。

本文我们就介绍这样一个解决方案,Bootstrap-Vue项目。

安装和设置

Bootstrap-Vue项目提供了Bootstrap项目中jQuery组件依赖了Vue替换方案,可以实现绝大多数案例和组件的替代。我们建议以Vue Cli插件方式使用,这样可以实现项目自动创建和配置,依赖项添加。首先我们安装Vue Cli。

安装Vue Cli

由于npm安装较慢,甚至会失败,需要,先安装国内镜像,可以使用cnpm或者npm别称:

然后用cnpm安装vue.js

  1. cnpm install -g @vue.js 

创建项目

  1. vue create hello-chongchong 

这样Vue CLI会自动创建一个Vue项目,提示选择项,选择"default"即可。

进入该项目目录:

  1. cd hello-chongchong 

使用下面的命令将Bootstrap-Vue插件添加到项目中。选项提示时,选择 "Y"。

  1. vue add bootstrap-vue 

这样无需任何复杂设置就可以设置好一个以vue启动的Bootstrap项目。

清除示例

 

默认情况下,Vue CLI为提供了一个示例HelloWorld应用程序。这都没啥用的,我们直接清除,包括App.vue和部件目录下的 HelloWorld.vue:

  1. >src/components/App.vue 
  2. rm src/components/HelloWorld.vue 

示例使用

创建模版

Bootstrap所有功能基本都可以在bootstrap-vue中以全局注册的组件来使用。这些组件通常和Bootstrap同名,为了以示区别,他们都以开头b-xxxx。

在此我们创建一个新的App.vue模板并添加一个Bootstrap容器:

  1. <template> 
  2. <b-container> 
  3. <p>Hello, Chongchong!</p> 
  4. </b-container> 
  5. </template> 

然后启用该服务

  1. npm run serve 

然后,浏览器访问,应该看到以下内容:

另外,如果查看页面源码,可以看到该b-container组件已使用常规的Bootstrap元素和类进行渲染:

  1. <div class="container"> 
  2. <p>Hello, Chongchong!</p> 
  3. </div> 

组件配置

许多组件都可以使用Vue道具进行配置。例如, b-btn组件,可以在页面中添加一个将按钮。b-btn有一个variant控制按钮主题,此处设置为primary。

  1. <template> 
  2. <b-container> 
  3. <p>Hello, Chongchong!</p> 
  4. <b-btn variant="primary">Click</b-btn> 
  5. </b-container> 
  6. </templat> 

Vue支持将动态值绑定到Bootstrap组件。例如,对b-alert组件添加一个alert提示信息。我们将其设success并提供一些提示信息。

  1. <template> 
  2. <b-container> 
  3. <p>Hello, Chongchong!</p> 
  4. <b-btn variant="primary">Click</b-btn> 
  5. <b-alert variant="success"> 
  6. You clicked the button! 
  7. </b-alert> 
  8. </b-container> 
  9. </template> 

可以将showprop绑定到本地data属性来有条件地显示信息showAlert。然后将showAlert响应组件click事件来切换的值b-btn。

  1. <template> 
  2. <b-container> 
  3. <p> Hello, Chongchong!</p> 
  4. <b-btn 
  5. variant="primary" 
  6. @click="showAlert = true" 
  7. > 
  8. Click 
  9. </b-btn> 
  10. <b-alert 
  11. v-bind:show="showAlert" 
  12. variant="success" 
  13. > 
  14. You clicked the button! 
  15. </b-alert> 
  16. </b-container> 
  17. </template> 
  18. <script> 
  19. export default { 
  20. data: () => ({ 
  21. showAlert: false 
  22. }) 
  23. }; 
  24. </script> 

比jQuery逻辑写起来简单多了。

Bootstrap-Vue指令

一些Bootstrap功能是作为指令而非组件提供的,因此可以轻松地将其添加到给已有元素。

例如,要添加工具提示功能,可以使用v-b-tooltip指令。下面我们使用指令参数hover向按钮添加一个,在按钮悬停时触发。

  1. <b-btn variant="primary" @click="showAlert = true" v-b-tooltip.hover title="This button triggers the alert"> Click </b-btn> 

注:tooltip插件需要popper.js的依赖项,但是使用Vue CLI安装Bootstrap-Vue,会自动include。

总结:

利用Bootstrap-Vue 来替换Bootstrap 4中的jQuery非常容易,而且可以带来vue cli的巨大的功能优势,大家可以尝试将手头的项目都替换一下。