用nuxt重构博客小记
苗锦洲
0
29
213
0
解析markdown目录,自定义axios等
友情提示:此篇文章大约需要阅读 11分29秒
# $nextTick()
[$nextTick()的理解*小崔*的博客-CSDN博客](https://blog.csdn.net/Cui_7788/article/details/103143373)
vue的dom是异步更新的,当v-if满足后,并不能立马获取到元素
```javascript
<div id=app>
<div id="div" v-if="showDiv">我是显示文本</div>
<button @click="showAndGetText">获取内容</button >
</div>
<script>
var app = new Vue({
el: '#app',
data () {
return {
showDiv : false
},
methods: {
showAndGetText () {
this.showDiv = true
this.$nextTick(function () {
let text = document.getElementById('div').innerHTML
console.log(text)
})
}
}
}
})
</script>
```
# 自定义markdown目录
## 解析目录
先用vditor解析为html,在after回调函数里获取元素中的所有h1到h6的元素,**设置自定义属性name=element.textContent,便于监听点击**然后解析成{index,headText}的数组,返回给父组件,然后再将不连续的index变为连续的,例如3,0,1,1,4变为0,0,1,1,2,两个指针,pre=-1和current,然后i从0开始遍历数组,current=[i].index,current>pre,current=pre+1,current<pre && current!=pre-1,current=0,pre=current,然后再解析为VTreeview需要的数据格式[{id,name,children}]
## 监听滚动
监听滚动,拿到index,设置VTreeview的active
## 监听点击
nextTick里拿到VTreeview,然后遍历对 `v-treeview-node__root`和 `v-treeview-node__label`设置点击事件,拿到name,然后根据之前遍历h1到h6设置的name获取元素,然后调用$vuetify.goTo()即可
# 自定义axios
## 创建新instance+自定义request拦截器
先创建js文件,配置不需要route的方法,例如request拦截器
```javascript
// static/js/myrequest.js
import axios from "axios";
import {getToken} from "~/static/js/utils/auth";
import errorCode from "~/static/js/utils/errorCode";
// Create a custom axios instance
const request = axios.create({
//TODO axios中请求配置有baseURL选项,表示请求URL公共部分
// baseURL: 'https://ordinaryroad.top',
baseURL: 'https://localhost',
// 超时
timeout: 10000,
// 携带cookie信息,保持session的一致性
withCredentials: true
})
// request.onRequest(config => {
// console.log('Making request to ' + config.url)
// console.log('onRequest', config)
// })
//
// request.onError(error => {
// console.log("onError", error)
// const code = parseInt(error.response && error.response.status)
// if (code === 400) {
// redirect('/400')
// }
// })
// request拦截器
request.interceptors.request.use(config => {
// 是否需要设置 token
const isToken = (config.headers || {}).isToken === false
if (getToken() && !isToken) {
config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
}
// get请求映射params参数
if (config.method === 'get' && config.params) {
let url = config.url + '?';
for (const propName of Object.keys(config.params)) {
const value = config.params[propName];
var part = encodeURIComponent(propName) + "=";
if (value !== null && typeof (value) !== "undefined") {
if (typeof value === 'object') {
for (const key of Object.keys(value)) {
// let params = propName + '[' + key + ']';
let params = propName;
var subPart = encodeURIComponent(params) + "=";
url += subPart + encodeURIComponent(value[key]) + "&";
}
} else {
url += part + encodeURIComponent(value) + "&";
}
}
}
url = url.slice(0, -1);
config.params = {};
config.url = url;
}
return config
}, error => {
console.log(error)
Promise.reject(error)
})
export default request
```
## 自定义response拦截器+this.$request
然后创建plugin,并在nuxt.config.js启用,配置需要route的方法,例如response拦截器
然后可以在vue中用 `this.$request`调用自定义拦截器后的axios
```javascript
// plugins/request.js
import request from '~/static/js/myrequest';
import errorCode from "~/static/js/utils/errorCode";
// export default function ({$axios}, redirect, inject) {
export default function ({$axios, route, app}, inject) {
const {store, router} = app;
// 响应拦截器
request.interceptors.response.use(res => {
// 未设置状态码则默认成功状态
const code = res.data.errorCode || 200;
// 获取错误信息
const msg = errorCode[code] || res.data.errorMsg || errorCode['default']
if (code === 2001) {
if (confirm('登录状态已过期\n螺线继续留在该页面请按取消键,重新登录请按确认键')) {
store.dispatch('user/LogOut').then(() => {
router.push({path: '/dashboard/user/login', query: {redirect: route.fullPath}})
})
}
/**
MessageBox.confirm('登录状态已过期,您可以继续留在该页面,或者重新登录', '系统提示', {
confirmButtonText: '重新登录',
cancelButtonText: '取消',
type: 'warning'
}
).then(() => {
store.dispatch('LogOut').then(() => {
location.href = '/index';
})
})
**/
return Promise.reject(new Error(msg))
} else if (code === 500) {
alert(msg)
/**
Message({
message: msg,
type: 'error'
})
**/
return Promise.reject(new Error(msg))
} else if (code !== 200) {
alert(msg)
/**
Notification.error({
title: msg
})
**/
// return Promise.reject('error')
return res.data
} else {
return res.data
}
},
error => {
console.log('err' + error)
let {message} = error;
if (message === "Network Error") {
message = "后端接口连接异常";
} else if (message.includes("timeout")) {
message = "系统接口请求超时";
} else if (message.includes("Request failed with status code")) {
message = "系统接口" + message.substr(message.length - 3) + "异常";
}
alert(msg)
/**
Message({
message: message,
type: 'error',
duration: 5 * 1000
})
**/
return Promise.reject(error)
}
)
// Inject to context as $request
inject('request', request)
}
```
评论
楼主暂时不想被别人评论哦~
已自动恢复阅读位置、日/夜间模式参数