2022年1月问题

Aditya2020-08-31开发问题

2020年8月问题汇总

  1. 像素转rem时过滤 vant 等组件库方案
  2. 利用js实现 禁用浏览器后退
  3. 实现对修饰器的支持: 实现对 babel 插件的使用
  4. js通过url下载音频到本地
  5. Vue项目中出现Loading chunk {n} failed问题的解决方法
  6. vue-router的keep-alive(前进刷新,后退不刷新)

1. 像素转rem时过滤 vant 等组件库方案

//.postcssrc.js

// const AutoPrefixer = require("autoprefixer");
const px2rem = require("postcss-px2rem");
module.exports = ({ file }) => {
    let remUnit
    // 判断条件 请自行调整 我使用的是 mand-mobile ui 没有对vant引入进行测试
    //link https://github.com/youzan/vant/issues/1181
    if (file && file.dirname && file.dirname.indexOf("vant") > -1) {
        remUnit = 37.5
    } else {
        remUnit = 75
    }
    return {
        plugins: [
            px2rem({ remUnit: remUnit})
            // AutoPrefixer({ browsers: ["last 20 versions", "android >= 4.0"] })
        ]
    }
}

2. 利用js实现 禁用浏览器后退

//防止页面后退
history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
    history.pushState(null, null, document.URL);
});

3. 实现对修饰器的支持: 实现对 babel 插件的使用

# 如果你的 Babel < 7.x 则安装 babel-plugin-transform-decorators-legacy
npm install --save-dev babel-plugin-transform-decorators-legacy
# 如果你的 Babel >= 7.x 则应该安装 @babel/plugin-proposal-decorators
npm install --save-dev @babel/plugin-proposal-decorators

#3.1 react-app-rewired 老版本配置方法

// 导入添加babel插件的函数
const { injectBabelPlugin } = require('react-app-rewired');
module.exports = function override(config, env) {
  config = injectBabelPlugin(["@babel/plugin-proposal-decorators", {"legacy": true}], config)
  return config;
};

#3.2 react-app-rewired 新版本配置方法( >=2.1.0 )

const { override, fixBabelImports, addPostcssPlugins, addLessLoader, useBabelRc, addBabelPlugins } = require('customize-cra');
const theme = require('./package.json').theme;

module.exports = override(
    fixBabelImports('import', {
        libraryName: 'antd-mobile',
        libraryDirectory: 'es',
        style: true,
    }),
    addLessLoader({
        javascriptEnabled: true,
        modifyVars: theme
    }),
    addPostcssPlugins([require("postcss-px2rem")({ remUnit: 75 })]),
    useBabelRc(),
    addBabelPlugins(["@babel/plugin-proposal-decorators", {"legacy": true}])
)

4. js通过url下载音频到本地

window.fetch(data.url.replace('http://', 'https://')).then(res => res.blob()).then(blob => {
    const a = document.createElement('a');
    document.body.appendChild(a)
    a.style.display = 'none'
    // 使用获取到的blob对象创建的url
    const url = window.URL.createObjectURL(blob);
    a.href = url;
    // 指定下载的文件名
    a.download = `${data.name}.mp3`;
    a.click();
    document.body.removeChild(a)
    // 移除blob对象的url
    window.URL.revokeObjectURL(url);
});
  1. window.open(url) 、a标签方式会直接进入播放页,无法达到下载的目的
  2. 不指定下载的文件名也会直接进入播放页
  3. 当前页面协议为https,音频如果使用http,会被拒绝

5. Vue项目中出现Loading chunk {n} failed问题的解决方法

这个通常是由于webpack打包重命名了改动过的css和js文件,并且删除了原有的文件,然后有两种场景:

  1. 用户正在浏览页面时你发包了,并且你启用了懒加载,这个时候用户的html文件中的js和css名称就和你服务器上的不一致,导致这个错误
  2. 用户浏览器有html的缓存,这种情况不管是否启用懒加载,都会有这个问题

其出现的根本原因是某个文件没有被找到,所以在使用vue-router的时候,router.onError捕捉到该错误时,重新渲染即可。

当在渲染一个路由的过程中,需要尝试解析一个异步组件时发生错误。

router.onError((error) => {
  const pattern = /Loading chunk (\d)+ failed/g;
  const isChunkLoadFailed = error.message.match(pattern);
  const targetPath = router.history.pending.fullPath;
  if (isChunkLoadFailed) {
    router.replace(targetPath);
  }
});

6. vue-router的keep-alive(前进刷新,后退不刷新)

#6.1 使用router.meta属性

// routes 配置
export default [
  {
    path: '/',
    name: 'home',
    component: Home,
    meta: {
      keepAlive: true // 需要被缓存
    }
  }, {
    path: '/:id',
    name: 'edit',
    component: Edit,
    meta: {
      keepAlive: false // 不需要被缓存
    }
  }
]

// app.vue
<keep-alive>
    <router-view v-if="$route.meta.keepAlive">
        <!-- 这里是会被缓存的视图组件,比如 Home! -->
    </router-view>
</keep-alive>

<router-view v-if="!$route.meta.keepAlive">
    <!-- 这里是不被缓存的视图组件,比如 Edit! -->
</router-view>

#6.2 使用include/exclude

// 组件 a
export default {
  name: 'a',
  data () {
    return {}
  }
}

// app.vue
<keep-alive include="a">
    <router-view>
        <!-- 只有路径匹配到的视图 a 组件会被缓存! -->
    </router-view>
</keep-alive>
Last Updated 2024/12/27 11:36:49