vue项目使用公共js方法@令狐张豪

我们在做项目中会用到很多js方法,然后有些方法是通用的我们需要进行封装使用

  1. 在src下创建utils目录并创建utils.js文件
  • utils.js文件
export default {
    //判断手机机型
    versions() {
        var u = navigator.userAgent;
        return {
            trident: u.indexOf('Trident') > -1,
            presto: u.indexOf('Presto') > -1,
            webKit: u.indexOf('AppleWebKit') > -1,
            gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,
            mobile: !!u.match(/AppleWebKit.*Mobile.*/) || !!u.match(/AppleWebKit/),
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
            android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1,
            iPhone: u.indexOf('iPhone') > -1,
            iPad: u.indexOf('iPad') > -1,
            iPod: u.indexOf('iPod') > -1,
            webApp: u.indexOf('Safari') == -1
        };
    },
    //设置缓存
    setItem(key, value) {
        localStorage.setItem(key, JSON.stringify(value));
    },
    // 获取缓存
    getItem(key) {
        return JSON.parse(localStorage.getItem(key));
    },
    // 清除所有缓存
    clearAll() {
        localStorage.clear();
    },
    //清除指定缓存
    clearAppoint(key) {
        localStorage.removeItem(key);
    },
}
  1. 在main.js里引入并注册
import utils from './utils/utils';
Vue.prototype.$utils = utils;
  1. 在组件里使用
    imagePreview(url) {
      let versions = this.$utils.versions();
      console.log(versions);
    },

end~~~

如有错误或观点不一致的请评论留言共同讨论,本人前端小白一枚,根据自己实际项目遇到的问题进行总结分享,谢谢大家的阅读!

你可能感兴趣的:(vue,javascript,vue.js,前端)