记录vue的一些踩坑日记

这篇博客记录了在Vue.js开发中遇到的问题及解决方案,包括安装Jq,解决vue列表页跳转后不刷新和保持位置问题,清理keep-alive缓存,时间戳转换,编程式路由错误处理,浏览器缓存问题,环境配置,Eslint报错,params参数丢失,H5页面控制台显示,项目启动,卸载和下载Node.js,以及vuex的commit和dispatch用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

记录vue的一些踩坑日记

安装Jq

npm install jquery --save

vue列表跳转到详情页,再返回列表的时候不刷新页面并且保持原位置不变;

解决:使用keepAlive

  1. 在需要被缓存的页面的路由中添加:keepAlive: true,
 {
        path: '/viewExamine',
        name: 'viewExamine',
        component: () => import('@/views/viewExamine'),
        meta: {
          keepAlive: true, 
        },
      },
  1. 记录位置

const router = new VueRouter({
  // mode: 'history',
  mode: 'hash', //刷新之后找不到页面用这个
  base: process.env.BASE_URL,
  routes,
  //记录位置
  scrollBehavior: (to, from, savedPosition) => { 
    if (savedPosition) {     
      return savedPosition
    } else { 
      return { x: 0, y: 0 }
    }
  }
})
  1. 在app.vue中:
<template>
  <div id="app" v-cloak>
    <!-- 可以被缓存的视图组件 -->
    <keep-alive>
      <router-view v-if="$route.meta.keepAlive"></router-view>
    </keep-alive>
    <!-- 不可以被缓存的视图组件 -->
    <router-view v-if="!$route.meta.keepAlive"></router-view> 
  </div>
</template>

然后,就可以啦,问题就解决了(返回列表页不会触发created)

vue退出登录后,如何清空keep-alive缓存

问题描述:在项目中,有个页面用到了keep-alive。但是,当我点击退出登录,切换了其他账号登录后,保留的还是上一个账号的数据信息,最终采取了以下方法解决的。

原文:https://blog.youkuaiyun.com/weixin_50446072/article/details/125541134

代码如下:(app.vue)

<template>
  <div id="app">
    <keep-alive v-if="isLoggedIn">
      <router-view v-if="$route.meta.keepAlive"></router-view>
    </keep-alive>
    <router-view v-if="!$route.meta.keepAlive||!isLoggedIn"></router-view>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isLoggedIn: false,
    };
  },
  watch: {
    $route(to, from) {
      // if the route changes...
      let token = localStorage.getItem("court-token") || "";
      if (token) {
        // firebase returns null if user logged out
        this.isLoggedIn = true;
      } else {
        this.isLoggedIn = false;
      }
    },
  },
};
</script>

转化时间戳

  1. 过滤器
Vue.filter('dateFormat_sfm', time => {
  //年月日时分秒
  var now = new Date(time);
  var nian = now.getFullYear();
  var yue = (now.getMonth() + 1).toString().padStart(2, "0");
  var ri = now.getDate().toString().padStart(2, "0");
  var shi = now.getHours().toString().padStart(2, "0");
  var fen = now.getMinutes().toString().padStart(2, "0");
  var miao = now.getSeconds().toString().padStart(2, "0");
  if (time === undefined) {
    return ``;
  } else {
    return `${nian}-${yue}-${ri} ${shi}:${fen}:${miao}`; //
  }
})
  1. mixin
  1. npm install moment --save(如果想使用moment)
  2. 在src下创建一个mixin文件夹 里面创建一个index.js
//import moment from 'moment'

const mixin = {
    methods: {
        getTimeSFM(time) {
            // if (time !== undefined) {
            //     return moment(time).format('YYYY-MM-DD HH:mm:ss')
            // } else {
            //     return ''
            // }
            //年月日时分秒
            var now = new Date(time);
            var nian = now.getFullYear();
            var yue = (now.getMonth() + 1).toString().padStart(2, "0");
            var ri = now.getDate().toString().padStart(2, "0");
            var shi = now.getHours().toString().padStart(2, "0");
            var fen = now.getMinutes().toString().padStart(2, "0");
            var miao = now.getSeconds().toString().padStart(2, "0");
            if (time === undefined) {
                return ``;
            } else {
                return `${nian}-${yue}-${ri} ${shi}:${fen}:${miao}`; //
            }
        },
        getTime(time) {

            // if (time !== undefined) {
            //     return moment(time).format('YYYY-MM-DD')
            // } else {
            //     return ''
            // }

            //年月日时分秒
            var now = new Date(time);
            var nian = now.getFullYear();
            var yue = (now.getMonth() + 1).toString().padStart(2, "0");
            var ri = now.getDate().toString().padStart(2, "0");
            var shi = now.getHours().toString().padStart(2, "0");
            var fen = now.getMinutes().toString().padStart(2, "0");
            var miao = now.getSeconds().toString().padStart(2, "0");
            if (time === undefined) {
                return ``;
            } else {
                return `${nian}-${yue}-${ri}`; //
            }
        }
    }
}
export default mixin

局部引入:(在需要用到的页面)

  • import mixin from “@/mixin/index”;
  • mixins: [mixin],

在这里插入图片描述
全局引入:(main.js)

  • import MiXin from ‘@/mixin/index’
  • Vue.mixin(MiXin)
  1. 可以直接使用在div里面: <div class="">领用日期:{{ getTime(item.useTime) }}</div>

在这里插入图片描述

解决编程式路由往同一地址跳转时会报错的情况


//解决编程式路由往同一地址跳转时会报错的情况
const originalPush = VueRouter.prototype.push;
const originalReplace = VueRouter.prototype.replace;
//push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch(err => err);
};
//replace
VueRouter.prototype.replace = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalReplace.call(this, location, onResolve, onReject);
  return originalReplace.call(this, location).catch(err => err);
};

在这里插入图片描述

多次打包之后:浏览器会有缓存

在 html 文件中加入 meta 标签,content 属性设置为no-cache;

public/index.html

  <meta http-equiv="pragram" content="no-cache">
  <meta http-equiv="cache-control" content="no-cache, no-store, must-revalidate">
  <meta http-equiv="expires" content="0">
项目打包的时候给每个打包文件加上 hash 值,一般是在文件后面加上时间戳;

在这里插入图片描述

vue.config.js

const { defineConfig } = require('@vue/cli-service');
const Timestamp = new Date().getTime();
module.exports = defineConfig({
  //  在打包时取消生成.map文件
  //在开发模式为true,有报错信息可以查看精确到行列(因为打包之后所有代码都打入一个js文件)
  productionSourceMap: process.env.NODE_ENV === 'production' ? false : true,
  transpileDependencies: true,
  lintOnSave: true, //eslint,默认是true
  publicPath: './',//因为webpack不认识@。 
  // 设置出口:解决打包缓存
  // 修改输出js目录名及文件名
  configureWebpack: {
    output: {
    //js表示在dist生成一个js文件夹
    //[name]自动根据生成名字
    //[hash:6]打包之后会生成一个hash值. :6表示取hash前6位
    //[chunkhash]打包会生成一个chunkhash值,只有每次修改配置chunkhash才会变化
      filename: `js/[name].[chunkhash].${Timestamp}.js`,
      chunkFilename: `js/[name].[chunkhash].${Timestamp}.js`
    }
  },
  // 修改输出css目录名及文件名
  css: {
    extract: {
      filename: `css/[name].[chunkhash].${Timestamp}.css`,
      chunkFilename: `css/[name].[chunkhash].${Timestamp}.css`
    }
  }, 

打包之后的文件:每次生成的文件名称都是不一样的

在这里插入图片描述

这是只设置了js文件名:在这里插入图片描述

vue配置环境:开发环境、测试环境、正式环境

项目根目录下新建文件:.env.development.env.production.env.test

在这里插入图片描述

NODE_ENV = 'development'//是node的语言 process.env.NODE_ENV就可以访问到值
VUE_APP_MODE = 'development'// 在vue中 要写成VUE_APP开头并大些
VUE_APP_BASE_API =  window.apiURL;//这里:'http://xxx:8080'(你的开发环境)
NODE_ENV = 'production'
VUE_APP_MODE = 'production'
VUE_APP_BASE_API = window.apiURL;//这里:'http://xxx:8080'(你的开发环境)
​​​​​​​NODE_ENV = 'test'
VUE_APP_MODE = 'test'
VUE_APP_BASE_API = window.apiURL;//这里:'http://xxx:8080'(你的开发环境)

package.json中配置:

  "scripts": {
    "serve": "vue-cli-service serve",
    "test": "vue-cli-service serve --mode test",
    "prod": "vue-cli-service serve --mode production",
    "build": "vue-cli-service build",
    "build:test": "vue-cli-service build --mode test",
    "build:prod": "vue-cli-service build --mode production", 
    "lint": "vue-cli-service lint"
  },

启动命令:

npm run serve;//开发环境
npm run test;//测试环境
npm run prod;//正式环境

打包命令:

npm run build;//开发环境
npm run build:test;//测试环境
npm run build:prod;//正式环境
window.apiURL:是获取当前项目启动的服务器的路径+端口(场景:没有固定的地址)
  • 新建文件:public/index.js
    在这里插入图片描述
  • index.js
const apiURL = window.location.origin
  • index.html中:
  <script type="text/javascript" src="<%= BASE_URL %>index.js"></script>
  <script>
    // 然后使用window对象
    window.apiURL = apiURL
  </script>
  • utils/request.js
// 1.创建一个新的axios实例,设置基地址
const request = axios.create({
  // baseURL:process.env.VUE_APP_BASE_API + "/xxx",
  baseURL: window.apiURL + "/xxx", // 正式
  timeout: 10000
});

这样的话,不管你的项目部署在那个地址下,都不用再改路径和端口了。

Eslint:常见打包报错

  • 注释://后面应该有空格;
  • Operator ‘===’ must be spaced 使用’= = =’ 而不是’= =’
  • Import in body of module; reorder to top import/first:将所有的import挡在最前面;
  • 使用 let/const 而不是var;

vue中使用params传参,刷新页面后params参数丢失解决方案

解决方案:

1. 配合sessionStorage实现刷新页面后数据不丢失

(网上很多都是使用localStorage配合使用,但是有个问题是将当前页面直接关闭了,重新进来后localStorage还是存在的。而使用sessionStorage,页面关闭后会自动删除)

export default {
	created(){
		   let paramsData = sessionStorage.getItem("paramsData");
		   let params;
	       if(paramsData){
	            params = JSON.parse(sessionStorage.getItem("paramsData"));
	        }else{
             	params = this.$route.params;
	            sessionStorage.setItem("paramsData", JSON.stringify(params));
	        }
	        this.params = params;
		},
	// 页面销毁之前
    beforeDestroy() {
        sessionStorage.removeItem('paramsData')
   	},
	}

2. 使用动态路由

使用动态路由,访问路由地址为:/vuew1/username/6110(感觉和query访问差不多,如果参数多点路由地址会显得很长,不大美观。)
在router.js中设置路由

const routes = [
  {
    path: '/view1/:name/:idno',
    name: 'view1',
    component: () => import( '../admin/view1.vue')
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

页面中使用

this.$router.push({name:'view1', params:{name:'张三', idno:'123123'}});
<router-link :to="{name:'view1', params: {name:'张三', idno:'123123'}}">跳转</router-link>

标题H5页面(在移动端)显示控制台

安装 VConsole

npm install vconsole

使用VConsole
Vue2

imort Vue from 'vue'
import VConsole from 'vconsole';
const vconsole = new VConsole()
Vue.use(vconsole)

Vue3

import { createApp } from 'vue'
import App from '@/App/index.vue'
import VConsole from 'vconsole';
const app = createApp(App)
const vconsole = new VConsole() as any
app.use(vconsole ) 

拿到一个vue项目,怎么启动?

运行别人的项目的前提准备
1、删除package-lock.json和node_modules 文件

package-lock.json记录了整个node_moudles文件夹的树状结构,还记录了模块的下载地址,但是它是基于项目作者的npm版本库生成的,若不删掉这个依赖文件,容易出现npm版本差异导致的报错。

2、进入项目的终端

2.1 首先,进入vue项目所在目录(如下图所示)
2.2 在当前路径框中输入【cmd】,回车
2.3 清除npm缓存

3、npm有缓存时,常常出现安装依赖不成功的现象,且一旦出现这个问题,报错信息很完善,但根据报错信息一项一项去解决,却死活解决不了,还找不出原因。控制台输入下面命令清除npm缓存,npm有缓存时,常常出现安装依赖不成功的现象

npm cache clean -f

4、重新安装依赖。

npm install

5、最后运行项目。

npm run serve

6、成功

上述是理想情况(不出错);

忘记截图了,下图和我的是一摸一样滴,,,
报错大概是这样

npm ERR! code 1 
npm ERR! path /Users/yc/Desktop/adminadmin-dmpc/node_modules/node-sass 
npm ERR! command failed 
npm ERR! command sh -c -- node scripts/build.js
npm ERR! Building: /usr/local/bin/node /Users/yc/Desktop/adminadmin-dmpc/node_modules/node-gyp/bin/node-gy
...

在这里插入图片描述

经过一番苦苦搜索,终于知道上述情况是因为node版本和scss版本不匹配,node版本过高的缘故,如何解决呢?

卸载 Node.js(https://www.php.cn/faq/533612.html

在使用 Node.js 过程中,如果出现安装不成功、版本不符、或出现其他问题等,需要删除已安装的 Node.js,重新安装新版本的 Node.js。此外,如果你需要使用其他的 JavaScript 开发环境,就需要卸载 Node.js。

如何卸载 Node.js?

在 Mac 中卸载 Node.js,可以选择以下两种方法:

使用命令行卸载 Node.js
第一步:打开终端,输入以下命令显示 Node.js 的安装路径:

which node

执行该命令后,会显示安装路径:/usr/local/bin/node

第二步:输入以下命令删除 Node.js 相关的文件:

sudo rm -rf /usr/local/bin/npm
sudo rm -rf /usr/local/share/man/man1/node.1
sudo rm -rf /usr/local/lib/dtrace/node.d
sudo rm -rf ~/.npm
sudo rm -rf ~/.node-gyp
sudo rm /usr/local/bin/node

该命令会删除 Node.js 的可执行文件、npm 包管理器、手册页、DTrace 跟踪文件和用户目录下相关文件。

第三步:确定是否完全卸载 Node.js。在终端中输入以下命令:

node -v

如果显示“command not found”,则表示已经卸载干净。

下载Node(https://www.php.cn/faq/528329.html

过官方网站下载指定版本的 Node.js

打开 Node.js 官方网站
在浏览器中输入 https://nodejs.org/,打开 Node.js 的官方网站。

选择下载版本
先去packjson.js里面查看node-sass版本,
在这里插入图片描述

然后对应你要下载的node版本

在这里插入图片描述
这里我需要下载node13版本(Mac)

在官网首页中,点击 “Download” 按钮,进入下载页面。在下载页面中,我们可以选择多种不同操作系统下的 Node.js 版本。

如果需要下载指定版本的 Node.js,可以在 “Previous Releases” 标签页中找到我们需要的版本,点击对应的版本号即可进入下载页面。

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

下载并安装 Node.js
在下载页面中,可以选择下载对应版本的 Node.js 安装程序进行安装。安装完成后,可以在终端中执行以下命令验证 Node.js 是否安装成功:

node -v

在这里插入图片描述

node安装好了,,,,,好累

然后再去执行npm install就不会报错了。。。。

报错

Failed to compile with 2 errors                                                                                                                                                                            下午2:15:52

Syntax Error: TypeError: token.type.endsWith is not a function
Occurred while linting D:\workspace\tk\h5\project\game\src\game\spy\components\Badge\index.vue:17
    at Array.every (<anonymous>)
    at Array.forEach (<anonymous>)
    at Array.forEach (<anonymous>)
    at Array.map (<anonymous>)


Syntax Error: TypeError: token.type.endsWith is not a function
Occurred while linting D:\workspace\tk\h5\project\game\src\game\spy\components\Icon\index.vue:11
    at Array.every (<anonymous>)
    at Array.forEach (<anonymous>)
    at Array.forEach (<anonymous>)
    at Array.map (<anonymous>)


You may use special comments to disable some warnings.
Use // eslint-disable-next-line to ignore the next line.
Use /* eslint-disable */ to ignore all warnings in a file.

您可以使用特殊注释禁用某些警告。 
使用//eslint-disable next行可以忽略下一行。 
使用/*eslint-disable*/可以忽略文件中的所有警告。

修改方法:在vue.config.js中直接添加一行代码即可:lintOnSave:false

module.exports = { 
  lintOnSave: false, // 关闭eslint
  }

“build:report”: “vue-cli-service build --report”,

在这里插入图片描述

vuex中this.$ store.commit和this.$store.dispatch的用法

参考文章

this.store.dispatch()与this.store.commit()方法的区别总的来说他们只是存取方式的不同,两个方法都是传值给vuex的mutation改变state

区别
this.$store.commit()------同步操作

this.$store.commit('方法名',)【存储】

this.$store.state.方法名【取值】

this.$store.dispatch()------异步操作

this.$store.dispatch('方法名',)【存储】

this.$store.getters.方法名【取值】

当操作行为中含有异步操作:
比如向后台发送请求获取数据,就需要使用action的dispatch去完成了。
其他使用commit即可。

  • commit => mutations,用来触发同步操作的方法。
  • dispatch =>actions,用来触发异步操作的方法。

在store中注册了mutation和action,在组件中用dispatch调用action,然后action用commit调用mutation。

store/index.js

import Vue from 'vue';
import Vuex from 'vuex';
import { setCookie, getCookie, removeCookie, os } from '@/utils';
import {  getUserPurse,  } from '@/api';

Vue.use(Vuex);

let expiresTime = 1 / 24;

const store = new Vuex.Store({
  state: { 
    app: null, 
    uid: getCookie('web_uid'),
    token: getCookie('token'),
    userInfo: {}, 
    purseInfo: null, // 钱包信息 
  },
  mutations: { 
    setUid(state, uid) {
      state.uid = uid;
      if (uid) {
        setCookie('web_uid', uid, os.app ? { expires: expiresTime } : undefined);
      } else {
        removeCookie('web_uid');
      }
    },
    setToken(state, token) {
      state.token = token;
      if (token) {
        setCookie('token', token, os.app ? { expires: expiresTime } : undefined);
      } else {
        removeCookie('token');
      }
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo;
    },
    setPurseInfo(state, purseInfo) {
      state.purseInfo = purseInfo;
    }, 
  },
  actions: { 
    logout({ commit }) { 
      commit('setUid', null);
      commit('setToken', null);
      commit('setUserInfo', {});
      commit('setPurseInfo', null); 
    },
     
    getUserPurse({ commit, state }, isUpdate) {
      return new Promise((resolve, reject) => {
        if (isUpdate || !state.purseInfo) {
          getUserPurse({
            data: {
              uid: state.uid,
              web_token: state.token
            }
          }).then(({ data }) => {
            console.log('getUserPurse',data);
            commit('setPurseInfo', data);
            resolve(data);
          }).catch((error) => {
            reject(error);
          });
        } else {
          resolve(state.purseInfo);
        }
      });
    },
    
    }
  }
});

export default store;

this.$store.commit

 methods: {
    // 登陆
    login() {
      let token = this.$route.query.token;
      login({
        data: {
          token
        },
        isReturnResult: true,
        isReturnError: true
      }).then(({ code, data, message }) => {
        if (code === 200) {
          this.$store.commit('setUid', data.uid);
          this.$store.commit('setToken', data.token);
          this.$router.replace({
            path: '/wallet'
          });
        } else if (code === 1404) {
          this.tips = message;
        } else {
          this.tips = '登录失败,请重新操作!';
        }
      }).catch(() => {
        this.$toast('请检查网络设置');
      });
    }
  }

this.$store.dispatch

methods: {
// 用户钱包信息
    getUserWalletInfo() {
      this.$store.dispatch("getUserPurse").then((data) => {
        // console.log('data',data);
        this.purseInfo = data;
        this.showPage = 1;
      }); 
    },
},
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值