【前端】采坑合集

10 篇文章 0 订阅

CSS

CSS设置小于12px的文字

-webkit-transform:scale(0.8);

height=“100%“无效

如果想让一个元素的百分比高度height: 100%;起作用,你需要给这个元素的所有父元素的高度设定一个有效值
例如

 html, body, div{ margin:0; height:100%; }

JS

invalid attempt to spread non-iterable instance

...扩展运算符使用错误

switch无效

case 判断Number值是容易出现,改为判断String就正常了

Uncaught SyntaxError: Unexpected token e in JSON at position 0

JSON.parse()处理的是非字符串参数,'accessToken'存的并不是字符串

报错代码

accessToken:  JSON.parse(sessionStorage.getItem('accessToken')) || null

修改后

accessToken: sessionStorage.getItem('accessToken') || null

console.log(…) is not a function

原因分析
console.log(data)与(res.data.data)之间缺少‘;’号

console.log(data)
(res.data.data).forEach((item,index)=>{
    this.dimensionData[index]=item
})

解决方案

console.log(data)
(res.data.data).forEach((item,index)=>{
    this.dimensionData[index]=item
})

a标签下载文件会打开pdf,download属性设置无效

问题描述

<a :href="form.pdf" :download="form.pdf.substr(form.pdf.lastIndexOf('/') + 1)" target="_blank">{{ form.pdf }}</a>      

原因分析
1.pdf是浏览器可以解析的文件,无论如何都无法直接弹出下载框
2. href属性的地址必须是非跨域的地址

问题解决
增加click事件:

// url为链接地址
downPdf(url) {
      const filename = url.substr(url.lastIndexOf('/') + 1)
      const x = new XMLHttpRequest()
      x.open('GET', url, true)
      x.responseType = 'blob'
      x.onload = (e) => {
        // 会创建一个 DOMString,其中包含一个表示参数中给出的对象的URL。这个 URL 的生命周期和创建它的窗口中的 document 绑定。这个新的URL 对象表示指定的 File 对象或 Blob 对象。
        const url = window.URL.createObjectURL(x.response)
        const a = document.createElement('a')
        a.href = url
        a.download = filename
        a.click()
      }
      x.send()
    },

vue

在Vuex的store文件中使用axios和vue-cookie

main.js虽然已经配置好axios、vue-cookie、store
但是在store配置文件中不能直接使用,需要重新引入

//store/index.js
import VueCookie from 'vue-cookie'
import axios from 'axios'
Vue.use(VueCookie)

VueCookie.get('username')
axios.post().then()

对象数组无法修改值并且直接复制也无法读取和修改值

方法一:直接修改
由于vue机制的原因,this.arr[0]=5这样的单个修改是无效的,应该用以下方法修改

this.$set(this.arr,[index],[value])

方法二:复制数组
由于vue机制的原因,直接let arr1=this.arr,数组内的对象没有gettersetter
正确方法:

  1. 用es6let arr1=[...this.arr] 或者let [...arr1]=this.arr
  2. let arr1 = thia.arr.concat()

页面切换,发生闪动

问题描述

设置了min-height,宽度100%,通过路由切换时,页面会闪动,查看发现是由于宽度变小有正常导致的晃动

原因分析
滚动条的出现又隐藏导致,高度小于min-height有滚动条时切换不会闪动

vw:浏览器窗口宽度的相对单位,这个宽度是包含滚动条的
100%:这个宽度是页面内容去容器的宽度,不包括滚动条

解决方案

html {
  overflow-y: scroll;
}
:root {
  overflow-y: auto;
  overflow-x: hidden;
}
:root body {
  position: absolute;
}
body {
  width: 100vw;
  overflow: hidden;
}

页面切换,高德地图autocomplete功能失效

原因: 各页面该功能id相同
解决: 不同页面使用不同的id

页面切换,定时器组件不停止销毁问题

问题:某一页面组件内有一定时期,跳转到另一页面定时器依然运行
原因:是页面销毁时定时器并未停止
解决:通过$once来监听定时器,在beforeDestroy钩子可以被清除。

let t = setInterval(event, 1000)
this.$once('hook:beforeDestroy', () => {            
    clearInterval(t);                                    
})

页面刷新,vuex数据丢失

问题描述

页面刷新,其他页面保存的vuex全局数据消失,导致本页面显示异常

原因分析

因为store里的数据是保存在运行内存中的,当页面刷新时,页面会重新加载vue实例,store里面的数据就会被重新赋值

解决方案

将state里的数据保存一份到本地存储(localStorage、sessionStorage、cookie)中

  1. localStorage永久存储在本地,除非主动删除;
  2. sessionStorage存储到当前页面关闭为止;
  3. cookie则根据设置的有效时间来存储,缺点是不能储存大数据且不易读取。

更倾向于选择sessionStorage,原因:

  1. vue是单页面应用,操作都是在一个页面跳转路由;
  2. sessionStorage可以保证打开页面时sessionStorage的数据为空,如果是localStorage则会读取上一次打开页面的数据。

方法一:针对某个state变量

//state
option:JSON.parse(sessionStorage.getItem('option'))||[],
//mutations
updateOption(state,payload) {
  state.option=payload
 },
//actions
getOptionInfo({state,commit}) {
    return new Promise((resolve)=>{
      axios.post(optionUrl).then((res) => {
        let data=res.data
        commit('updateOption', data)
        sessionStorage.setItem("option",JSON.stringify(state.option))
      }).catch((err) => {
        console.log(err)
      })
    })
  },

方法二:针对所有state数据

export default {
  name: 'App',
  created () {
    //在页面加载时读取sessionStorage里的状态信息
    if (sessionStorage.getItem("store") ) {
        this.$store.replaceState(Object.assign({}, this.$store.state,JSON.parse(sessionStorage.getItem("store"))))
    } 

    //在页面刷新时将vuex里的信息保存到sessionStorage里
    window.addEventListener("beforeunload",()=>{
        sessionStorage.setItem("store",JSON.stringify(this.$store.state))
    })
  }
}

页面切换,子组件数据不更新&页面未重新渲染&页面重复渲染

问题1:虽然页面不同,但是每个页面有与其他页面相同的id,在路由切换时,之前界面的元素会叠加渲染到新页面上。
解决:修改id,使其都不相同

问题2:路由切换,复用的子组件的下拉选项没有随之变化。

原因是keep-alive是Vue的内置组件,能在组件切换过程中将状态保留在内存中,防止重复渲染DOM,写在mouted钩子函数中的代码并没有被执行。

解决: 使用activated钩子函数(keep-alive组件激活时调用),将跟随路由变化的部分写在activated,其他的保留在mounted

activated() {
      this.$store.commit('option', "XX")
      this.options=this.options
      this.initChange()
    },
    mounted(){
      this.initNoChange()
    },

页面切换,keep-alive导致的数据重复加载&不加载

页面切换keep-alive导致的数据问题

elementUI的css部分失效

原因分析

由于修改的是elementUI组件的样式,在scope作用域因为权重的问题,elementUI组件相当于子组件,该vue组件相当于父组件,父组件中是不能直接修改子组件的样式的,需要在父组件中使用vue的深度作用选择器

解决方案

<style lang="scss" scoped>
	/deep/.index {
		span{}
	}

使用/static下的图片开发正常但部署后不显示

问题描述

  1. template通过img引入 <img src="/static" />
  2. .vue 的script通过import引入公共样式@import url("../../../static/css/style.css");
  3. 公共样式中背景图片引入url("/static/img/bg.jpg")

原因分析

因为项目是通过tomcat部署在子目录下的,而不是根目录 所以使用绝对路径/static是访问不到图片的,必须使用相对路径

  • 直接将/static修改为./static开发环境会报错

解决方案

注意自己项目的相对位置,必须该文件相对于static图片的路径

  1. template通过img引入:<img src="../../../static/img/bj-1.png" />
  2. 公共样式中背景图片引入:url("../../static/img/bg.jpg")

npm run build后 index.html不能正常显示

可能一:文件引用路径问题
config文件下index.js的build:下修改

assetsPublicPath:'./'

可能二:路由history模式问题

当你使用了路由之后,在没有后端配合的情况下就打开路由history模式的时候,打包出来的文件也会是一片空白的情况

router(路由)文件(index.js)注释掉history模式

// mode: 'history',

可能三: 图片加载问题
http://www.jb51.net/article/134385.htm

在IE浏览器下页面显示空白

需要babel-polyfill处理器

cnpm install babel-polyfill --save-dev

main.js

import 'babel-polyfill';

-webpack.base.config.js

entry: {
    app: ['babel-polyfill', './src/main.js']
  },

vue3+vite:浏览器点击菜单路由报错Failed to fetch dynamically imported module

表现:同样的谷歌浏览器,有些用户正常、有些用户报错
原因:代码修改后重新部署,js编译后文件哈希值改变
解决:刷新浏览器获取最新代码

vue-devtools正常但是控制台不显示

vue.min.js无效,开发环境时可修改为vue.js,等生产环境时再修改为vue.min.js

Vue router:NavigationDuplicated {_name: “NavigationDuplicated“, name: “NavigationDuplicated“}

报错代码

router.push({name:'login'})

修改后

router.push({name:'login'}).catch((err)=>{err})

Refused to execute script from XXX because its MIME type (‘text/plain‘) is not executable

问题描述
vue项目,本地运行正常,打包部署后无法正常打开,控制台报错

Refused to apply style from 'http://XXX:8089/static/css/app.e4ed391c2baa524e5eb7a76a9823dadf.css' because its MIME type ('text/plain') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

Refused to execute script from 'http://XXX:8089/static/js/manifest.5ed7af06317fe4810457.js' because its MIME type ('text/plain') is not executable, and strict MIME type checking is enabled.

 Refused to execute script from 'http://XXX:8089/static/js/vendor.a010a19c23b36edc4ad5.js' because its MIME type ('text/plain') is not executable, and strict MIME type checking is enabled.

Refused to execute script from 'http://XXX:8089/static/js/app.a102df9abbb4bcf3015c.js' because its MIME type ('text/plain') is not executable, and strict MIME type checking is enabled.

原因分析
当请求的css、js 文件的MIME 类型 为 text/plain 时,会被当做 .txt 文件来处理,浏览器就会拒绝渲染
最终方法
配置问题,发现nginx.conf配置注释掉了以下内容

include       /XXX/nginx/conf/mime.types;
default_type  application/octet-stream;

无效尝试

  1. 误以为vue index.html引入css、js文件方式错误,但无论static/js/XX还是./static/js/XX都无法解决。
  2. 误以为配置add_header X-Content-Type-Options 'nosniff';导致,但其实vue build后css、js的type=text/csstype=application/javascript是符合该策略的。

Error from chokidar (D:): Error: EBUSY: resource busy or locked, lstat ‘D:\pagefile.sys‘

问题描述

该项目是拷贝的另一个项目(可正常运行),原项目曾将elementui的引入改为cdn引入,但是本地开发和打包运行都无误,拷贝后的项目npm install后,dev启动报错

 ERROR  Failed to compile with 1 errors                                                                   上午10:40:34
This dependency was not found:

* element-ui/lib/theme-chalk/index.css in ./src/main.js

To install it, you can run: npm install --save element-ui/lib/theme-chalk/index.css
Error from chokidar (D:\): Error: EBUSY: resource busy or locked, lstat 'D:\pagefile.sys'

原因分析

  1. 一开始百度的方法都是删除node_modulesnpm cache clean --force后重新npm install,都无用
  2. 根据报错提示npm install --save element-ui/lib/theme-chalk/index.css,依然报错
  3. package.json增加element-ui,依然报错
  4. 删除原项目的依赖后重新npm install,发现也无法再正常运行
  5. 重新安装了nodejs和npm,依然无法解决
  6. 不使用CDN引用方式,改回最原始的npm第三方依赖引入方式,运行正常

由此可知,问题出在elementui的cdn引入方式

问题解决
重新研究vue/webpack的cdn引入:
【vue/webpack3】【element-ui】引入CDN资源

终极原因分析

旧的出问题的引入方式与新的方式差别在两个地方:

  1. 旧项目能正常运行的时候node_modules有残留的‘element-ui’
  2. main.js的旧的通过require方式引入

因为旧的方式之前运行打包都没问题,以为问题出在package.json里去掉了‘element-ui’,但按原理运行时引入的应该是window域下的‘element-ui’,node_modules里有没有并不影响

最终发现:问题出现在的就main.js配置中的import ElementUI from 'element-ui'注释掉了,但import 'element-ui/lib/theme-chalk/index.css'未注释掉,所以才会报错This dependency was not found: * element-ui/lib/theme-chalk/index.css in ./src/main.js

经验教训:认真分析自己的错误信息,直接百度不靠谱!!!

Error occurred while trying to proxy request / from localhost:8070 to (ETIMEDOUT)

问题描述

[HPM] Error occurred while trying to proxy request /index/login from localhost:8070 to http://XXXX:18891/ (ETIMEDOUT)

原因分析

后端服务器(阿里云)18891端口没开

解决方案

  1. 换一个已开的端口
  2. 阿里云开放18891端口
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值