vue项目中全局引用jquery :
1、“ npm install jquery --save ” 命令安装jquery
2、在项目根目录下的 build 目录下找到webpack.base.conf.js 文件,在开头使用以下代码引入webpack,如下
var webpack = require('webpack')
3、在webpack.base.conf.js 配置文件的module.exports对象中添加一段代码如下
plugins: [new webpack.ProvidePlugin({$: "jquery",jQuery: "jquery",jquery: "jquery","window.jQuery": "jquery"})],
4、“ npm run dev ” 命令重新运行项目
5、在main.js文件中引入如下:
import $ from 'jquery'
6、测试:在组件中直接使用jquery选择器
<template><div class="childContainer"><div id="testJquery">这行文字的颜色将用来测试全局jquery是否引用成功</div></div>
</template><script>export default {name:"Child",data(){return {}},mounted(){$("#testJquery").css({'color':'red','font-weight':'bold'}); //也可以使用jQuery("#testJquery").css()},}
</script>
vue项目中引用外部js插件
第一种外部js文件为纯函数js文件:
项目结构如下图:
1、公共JavaScript函数 util.js ,注意最后要使用 export {funcName} 的形式导出需要的函数
//数字相加
function addNum(a,b){return a+b;
}// 判断数组元素是否重复
function isArrRepeat(arr) {var _arr = arr.sort();console.log(_arr)for (var i = 0; i < _arr.length; i++) {if (_arr[i] === _arr[i + 1]) {return true;}}return false;}// 判断数据类型
function type(elem) {if (elem == null) {return elem + '';}return toString.call(elem).replace(/[\[\]]/g, '').split(' ')[1].toLowerCase();}//返回浏览器版本function getExplorerInfo() {let explorer = window.navigator.userAgent.toLowerCase();// ieif (explorer.indexOf("msie") >= 0) {let ver = explorer.match(/msie ([\d.]+)/)[1];return {type: "IE",version: ver};}// firefoxelse if (explorer.indexOf("firefox") >= 0) {let ver = explorer.match(/firefox\/([\d.]+)/)[1];return {type: "Firefox",version: ver};}// Chromeelse if (explorer.indexOf("chrome") >= 0) {let ver = explorer.match(/chrome\/([\d.]+)/)[1];return {type: "Chrome",version: ver};}// Operaelse if (explorer.indexOf("opera") >= 0) {let ver = explorer.match(/opera.([\d.]+)/)[1];return {type: "Opera",version: ver};}// Safarielse if (explorer.indexOf("Safari") >= 0) {let ver = explorer.match(/version\/([\d.]+)/)[1];return {type: "Safari",version: ver};}
}//导出声明的公共函数
export {addNum, getExplorerInfo
}
2、vue模板组件中使用引用的外部js函数, 注意要使用 import {} from '../js/path' 引用导出的js函数
<template><div class="hello"><h3 id="h">{{testMsg}}</h3><div><button @click="changeTxt()">修改dom文本内容</button><button @click="add(5,8)">计算5+8</button><button @click="getExplInfo()">获取当前浏览器信息</button></div></div>
</template><script>
import {addNum,getExplorerInfo} from '../assets/js/util.js' //引入外部js中的函数
export default {name: 'HelloWorld',data () {return {testMsg:"原始值",}},methods:{changeTxt:function(){let that=this;that.testMsg="修改后的文本值"; //修改dom数据},add:function(a,b){let c=addNum(a,b); //使用外部js中的函数console.log(c);},getExplInfo:function(){let info=getExplorerInfo();console.log(info);}}
}
</script>
第二种外部js是自执行匿名函数:
1、该匿名函数js根据浏览器尺寸修改字体尺寸大小
(function (doc, win) {let aa=123;console.log(aa);let docEl = doc.documentElement,resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',recalc = function () {var clientWidth = docEl.clientWidth;if (!clientWidth) return;if (clientWidth >= 840) {docEl.style.fontSize = '70px';} else if (clientWidth >= 640) {docEl.style.fontSize = '50px';} else {docEl.style.fontSize = 50 * (clientWidth / 640) + 'px';}};if (!doc.addEventListener) return;win.addEventListener(resizeEvt, recalc, false);doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);
2、在vue组件模板中使用import引入外部自执行的js
import '../assets/js/autoDone.js' //引入外部匿名函数
第三种外部js是封装的插件js:
这里以引用niceScroll.js滚动条插件为例
1、niceScroll.js下载网盘链接:https://pan.baidu.com/s/1p_rkxCAq8bKS7x5e_-N4Cg
提取码:dt88
2、vue组件模板使用import导入外部niceScroll.js,
<template><div class="hello"><div id="boxscroll">THIS IS A SIMPLE SCROLLABLE DIV<h2> Package Description </h2><p>Release Date: August 10, 2010</p><p>The <a title="http://www.openprinting.org/show_driver.cgi?driver=hpijs" rel="nofollow" href="http://www.openprinting.org/show_driver.cgi?driver=hpijs">HPIJS</a> driver is the free, <a title="http://hplipopensource.com/hplip-web/index.html" rel="nofollow" href="http://hplipopensource.com/hplip-web/index.html">open-source driver</a> issued by HP for their DeskJet and LaserJet printers. For most <a title="" href="http://www.linuxfoundation.org/collaborate/workgroups/openprinting/macosx/hpijs#Printers">supported printers</a>, this driver produces output quality equivalent to the proprietary HP drivers. In photo mode, with photo paper, the output quality is very high, especially for the HP DeskJet 990C and later models, which auto-detect the paper type in hardware. Photo printing is fully supported in the newer 6- and 7-ink models.</p><p>A major advantage of using this driver over those supplied by HP is the direct interface between HPIJS and the native CUPS spooler, which allows printing from any printer over any available connection such as USB, AppleTalk, TCP/IP (via LPD and IPP), HP JetDirect, and shared windows printers via SAMBA. Additionally, this driver utilizes the existing Mac OS X USB "backend" and thus does not install any software that might interfere with standard USB operation.</p><p>Please note:</p><ul><li>HP does not provide any support for HPLIP or HPIJS on the Mac OS X platform.</li><li><a href="http://www.linuxfoundation.org/en/OpenPrinting/MacOSX/hpijs-USB">Several HP USB devices</a> may not print successfully over the standard Mac OS X USB "backend". Please <a href="http://www.linuxfoundation.org/en/OpenPrinting/MacOSX/hpijs-USB">see this note</a> for more information.</li></ul><h2>Release Notes</h2><ul><li>This release fixes a problem with the PPDs that caused many job options such as page orientation, color/grayscale mode, duplex printing, etc. to fail.</li><li>HPIJS is HP's universal printer driver for most of their non-PostScript printers. It comes as a part of HPLIP, HP Linux Imaging and Printing.</li><li>The PPDs for HP printers are now sourced from the HPLIP package rather than the OpenPrinting.org database.</li><li>PPDs for printers from other manufacturers are provided by OpenPrinting.org.</li><li>Some printers are only partially supported. Printers such as<br />HP LaserJet 1022<br />HP LaserJet p1505n<br />HP LaserJet p12014<br />HP LaserJet p2035<br />require a proprietary plug-in for full support. This package does not contain or support such plug-ins.</li></ul><p><a name="Printer_Set_Up_Instructions" id="Printer_Set_Up_Instructions"></a></p><h2> Printer Set Up Instructions </h2><p>To add a printer queue, Leopard (Mac OS X 10.5.x) users should use the Print & Fax from System Preferences. Click on the + (plus) icon at the lower left. A new window will open. In that window, click the Default Browser icon at the top left. Highlight your printer in the section below. Use the "Print Using" pop-up menu near the bottom of the window to select the correct PPD for your printer and click Add.</p><p>Tiger users should open the Printer Setup Utility and click on the Add icon at the top of the Printer List window. A new window will open. In that window, click the Default Browser icon at the top left. Highlight your printer in the section below. Use the "Print Using" pop-up menu near the bottom of the window to select the correct PPD for your printer and click Add.</p><p>Jaguar (OS X 10.2.x) and Panther (OS X 10.3.x) users should open Print Center (Jaguar) or Printer Setup Utility (Panther), hold down the Option key, and click the Add Printer button in the Print Center toolbar. Within the setup sheet, choose Advanced from the top popup menu; then in the "Device:" popup menu select your printer by name (it should be the last item in the menu list). Finally, select the correct PPD from the model browser and click Add.</p></div></div>
</template>
<style>
#boxscroll {padding: 40px;height: 220px;width: 300px;border: 2px solid #00F;overflow: auto;margin-bottom:20px;
}
</style><script>
import '../assets/js/jquery.niceScroll.min.js' //引入外部js插件export default {name: 'HelloWorld',data () {return {}},mounted(){$("#boxscroll").niceScroll({cursorborder:"",cursorcolor:"#00F",boxzoom:true}); // First scrollable DIV},
}
</script>
注意:该滚动条插件依赖于jquery,所以需要先全局引用jquery
PS附加:niceScroll.js滚动条插件使用方法
niceScroll 配置选项:
$("#boxscroll").niceScroll({cursorcolor: "#424242", // 改变滚动条颜色,使用16进制颜色值cursoropacitymin: 0, // 当滚动条是隐藏状态时改变透明度, 值范围 1 到 0cursoropacitymax: 1, // 当滚动条是显示状态时改变透明度, 值范围 1 到 0cursorwidth: "5px", // 滚动条的宽度,单位:便素cursorborder: "1px solid #fff", // CSS方式定义滚动条边框cursorborderradius: "5px", // 滚动条圆角(像素)zindex: "auto" | 3, // 改变滚动条的DIV的z-index值scrollspeed: 60, // 滚动速度mousescrollstep: 40, // 鼠标滚轮的滚动速度 (像素)touchbehavior: false, // 激活拖拽滚动hwacceleration: true, // 激活硬件加速boxzoom: false, // 激活放大box的内容dblclickzoom: true, // (仅当 boxzoom=true时有效)双击box时放大gesturezoom: true, // (仅 boxzoom=true 和触屏设备时有效) 激活变焦当out/in(两个手指外张或收缩)grabcursorenabled: true, // (仅当 touchbehavior=true) 显示“抓住”图标display "grab" iconautohidemode: true, // 隐藏滚动条的方式, 可用的值:// true // 无滚动时隐藏// "cursor" | // 隐藏// false | // 不隐藏,// "leave" | // 仅在指针离开内容时隐藏// "hidden" | // 一直隐藏// "scroll", // 仅在滚动时显示background: "", // 轨道的背景颜色iframeautoresize: true, // 在加载事件时自动重置iframe大小cursorminheight: 32, // 设置滚动条的最小高度 (像素)preservenativescrolling: true, // 你可以用鼠标滚动可滚动区域的滚动条和增加鼠标滚轮事件railoffset: false, // 可以使用top/left来修正位置bouncescroll: false, // (only hw accell) 启用滚动跳跃的内容移动spacebarenabled: true, // 当按下空格时使页面向下滚动railpadding: { top: 0, right: 0, left: 0, bottom: 0 }, // 设置轨道的内间距disableoutline: true, // 当选中一个使用nicescroll的div时,chrome浏览器中禁用outlinehorizrailenabled: true, // nicescroll可以管理水平滚动railalign: right, // 对齐垂直轨道railvalign: bottom, // 对齐水平轨道enabletranslate3d: true, // nicescroll 可以使用CSS变型来滚动内容enablemousewheel: true, // nicescroll可以管理鼠标滚轮事件enablekeyboard: true, // nicescroll可以管理键盘事件smoothscroll: true, // ease动画滚动sensitiverail: true, // 单击轨道产生滚动enablemouselockapi: true, // 可以用鼠标锁定API标题 (类似对象拖动)cursorfixedheight: false, // 修正光标的高度(像素)hidecursordelay: 400, // 设置滚动条淡出的延迟时间(毫秒)directionlockdeadzone: 6, // 设定死区,为激活方向锁定(像素)nativeparentscrolling: true, // 检测内容底部便于让父级滚动enablescrollonselection: true, // 当选择文本时激活内容自动滚动cursordragspeed: 0.3, // 设置拖拽的速度rtlmode: "auto", // DIV的水平滚动从左边开始cursordragontouch: false, // 使用触屏模式来实现拖拽oneaxismousemode: "auto", // 当只有水平滚动时可以用鼠标滚轮来滚动,如果设为false则不支持水平滚动,如果设为auto支持双轴滚动scriptpath: "", // 为boxmode图片自定义路径 ("" => same script path)preventmultitouchscrolling: true // 防止多触点事件引发滚动});
注意:项目中单个组件可能会使用多个niceScroll对象时,要及时隐藏用完的nicescroll对象,加载时,需要先show,再resize。
1、隐藏滚动条
$("#mydiv").getNiceScroll().hide();
2、当浏览器窗口尺寸改变时候,主要重置滚动条大小
$("#mydiv").getNiceScroll().resize();
3、滚动条到指定位置
$("#mydiv").getNiceScroll(0).doScrollLeft(x, duration); // Scroll X Axis
$("#mydiv").getNiceScroll(0).doScrollTop(y, duration); // Scroll Y Axis
参考网址:
https://blog.csdn.net/mss359681091/article/details/52838179