vue router路由改变后样式查询加载
时间: 2023-08-02 11:25:19 浏览: 48
当Vue Router路由发生改变后,可以在`mounted`和`updated`生命周期钩子函数中使用`$nextTick`方法来获取路由信息并加载对应的样式。例如,可以在Vue组件中添加以下代码:
```javascript
mounted() {
this.loadStyles()
},
updated() {
this.loadStyles()
},
methods: {
loadStyles() {
const currentPath = this.$route.path
const links = document.getElementsByTagName('link')
for (let i = 0; i < links.length; i++) {
const link = links[i]
if (link.rel === 'stylesheet' && link.getAttribute('data-path') && link.getAttribute('data-path') !== currentPath) {
link.parentNode.removeChild(link)
}
}
const head = document.getElementsByTagName('head')[0]
const link = document.createElement('link')
link.rel = 'stylesheet'
link.type = 'text/css'
link.href = `/styles/${currentPath}.css`
link.setAttribute('data-path', currentPath)
head.appendChild(link)
}
}
```
这段代码中,首先获取当前路由的路径,然后遍历页面中的所有link标签,如果该标签的rel属性值为stylesheet并且该标签的data-path属性值不等于当前路由路径,则从页面中删除该标签。接着,创建一个新的link标签,并将其href属性设置为当前路由路径对应的样式文件路径,最后将该标签添加到head标签中即可。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)