vue实现操作日志记录
实现操作日志记录的方法
使用 Vuex 和 Axios 拦截器
在 Vue 项目中,可以通过 Vuex 管理日志状态,结合 Axios 拦截器捕获请求和响应,记录操作日志。
安装必要的依赖:
npm install axios vuex
创建 Vuex store 模块管理日志:
// store/modules/log.js
const state = {
logs: []
}
const mutations = {
ADD_LOG(state, log) {
state.logs.push(log)
}
}
const actions = {
addLog({ commit }, log) {
commit('ADD_LOG', log)
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
配置 Axios 拦截器:

// utils/request.js
import axios from 'axios'
import store from '@/store'
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API,
timeout: 5000
})
service.interceptors.request.use(config => {
if (config.method !== 'get') {
store.dispatch('log/addLog', {
action: `${config.method} ${config.url}`,
params: config.data || {},
timestamp: new Date().toISOString()
})
}
return config
})
export default service
使用自定义指令记录用户操作
创建全局指令记录 DOM 操作:
// directives/log.js
export default {
inserted(el, binding) {
el.addEventListener('click', () => {
const action = binding.value || el.innerText
this.$store.dispatch('log/addLog', {
action,
timestamp: new Date().toISOString()
})
})
}
}
注册指令:
// main.js
import logDirective from '@/directives/log'
Vue.directive('log', logDirective)
使用指令:

<button v-log="'用户点击了提交按钮'">提交</button>
使用 Vue Router 导航守卫记录页面访问
记录路由跳转信息:
// router/index.js
router.beforeEach((to, from, next) => {
store.dispatch('log/addLog', {
action: `访问页面: ${to.path}`,
params: to.query,
timestamp: new Date().toISOString()
})
next()
})
日志持久化存储
添加定期将日志发送到服务器的逻辑:
// utils/log.js
export function uploadLogs() {
const logs = store.state.log.logs
if (logs.length > 0) {
axios.post('/api/logs', { logs }).then(() => {
store.commit('log/CLEAR_LOGS')
})
}
}
// 每5分钟上传一次
setInterval(uploadLogs, 5 * 60 * 1000)
日志展示组件
创建日志展示组件:
<template>
<div class="log-container">
<div v-for="(log, index) in logs" :key="index">
[{{ log.timestamp }}] {{ log.action }}
</div>
</div>
</template>
<script>
export default {
computed: {
logs() {
return this.$store.state.log.logs
}
}
}
</script>
以上方法可以根据项目需求组合使用,实现完整的操作日志记录功能。






