vue项目常见问题汇总

189 阅读2分钟

1、配置代理解决跨域

在vue.config.js文件中

//只用于开发环境
devServer:{
  proxy: {
     //只对请求路由以/api开头的请求进行代理转发
    "/api": {
       //转发的目标URL
       target: "http://localhost:3000",
       //支持跨域
       changeOrigin: true,
       //路径重写
       pathRewrite: {"^/api" : ""}
     }
   }
}

1、让vscode提示@开头的模块路径引入

在根目录创建jsconfig.json文件,书写内容如下

{
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
        "@/*": ["src/*"]
    }
  },
  "exclude": ["node_modules", "dist"]
}

2、编程式导航重复跳转路由的错误

  1. 问题: image.png

  2. 原因分析
    vue-router3.1.0之后, 引入了push()的promise的语法, 如果没有通过参数指定回调函数就返回一个promise来指定成功/失败的回调, 且内部会判断如果要跳转的路径和参数都没有变化, 会抛出一个失败的promise

说明文档: github.com/vuejs/vue-r…

  1. 解决
  • 方案1: 在进行跳转时, 指定跳转成功的回调函数或catch错误
// catch()处理错误
this.$router.push(`/search/${this.keyword}`).catch(() => {})
// 指定成功的回调函数
this.$router.push(`/search/${this.keyword}`, () => {})
// 指定失败的回调函数
this.$router.push(`/search/${this.keyword}`, undefined, () => {})
  • 方案2: 修正Vue原型上的push和replace方法
// 缓存原型上的push函数
const originPush = VueRouter.prototype.push
const originReplace = VueRouter.prototype.replace
// 给原型对象上的push指定新函数函数
VueRouter.prototype.push = function (location, onComplete, onAbort) {
  // 判断如果没有指定回调函数, 通过call调用源函数并使用catch来处理错误
  if (onComplete===undefined && onAbort===undefined) {
    return originPush.call(this, location, onComplete, onAbort).catch(() => {})
  } else { // 如果有指定任意回调函数, 通过call调用源push函数处理
    originPush.call(this, location, onComplete, onAbort)
  }
}
// replace同理处理
VueRouter.prototype.replace = function (location, onComplete, onAbort) {
  if (onComplete===undefined && onAbort===undefined) {
    return originReplace.call(this, location, onComplete, onAbort).catch(() => {})
  } else {
    originReplace.call(this, location, onComplete, onAbort)
  }
}
  1. 补充说明
  • 问题: 为什么声明式路由跳转没有此问题?
  • 答: 因为默认传入了成功的空回调函数

vue2+element-ui中常见bug

1、Property or method "model" is not defined on the instance but referenced during render....

image.png

image.png 问题:v-model写法不合法
解决:

image.png

2、Missing required prop: "value"

image.png

image.png 问题:没有初始数据,缺少v-model
解决 image.png