vue 中刷新路由几种方法
1、第一种方法:provide 与 inject结合使用(亲测有效的比较实用的方法)
1、1 注册
/**
App.vue
*/
<template>
<div id="app">
<router-view v-if="isRouterAlice"/>
</div>
</template>
<script>
export default {
name: 'App',
provide() {
return {
reload: this.reload
}
},
data() {
return {
isRouterAlice: true
}
},
methods: {
reload() {
this.isRouterAlice = false
this.$nextTick(function() {
this.isRouterAlice = true
})
}
}
}
</script>
1、2 使用
/**
刷新页面操作的页面,如我案例中切换数据中心的页面
*/
<template>
<el-scrollbar wrap-class="scrollbar-wrapper">
<!-- 集群 -->
<el-select
v-if="!isCollapse"
v-model="currentCluster.value"
class="data-center-selector"
@change="switchCluster(currentCluster.value)">
<el-option
v-for="(item, index) in clusterList"
:key="index"
:label="item.lable"
:value="item.value"
/>
</el-select>
</template>
<script>
import { mapActions } from 'vuex'
export default {
components: { SidebarItem },
inject: ['reload'],
data() {
return {
clusterList: [
{
label:qingdao,
value: '青岛数据中心'
},
{
label: shanghai,
value: '上海数据中心'
}
],
currentCluster: {
value: ''
}
}
},
methods: {
...mapActions([
'SwitchCluster' // 设置localstorage 和当前集群
]),
// 切换集群,设置当前store的当前集群
switchCluster(clusterValue) {
// 通过当前的集群获取集群对应的label的object用于api
const current_cluster = this.clusterList.find(item => item.value === clusterValue)
// 设置localstorage 和当前集群后重新刷新页面请求api
this.SwitchCluster(current_cluster).then(res => {
this.reload()
}).catch(err => {
console.log(err)
})
},
/**
store的app.js 主要用于设置localstorage的数据中心id和当前的数据中心
*/
import { setCluster, getCluster, getClusterList } from '@/utils/cluster'
const app = {
state: {
clusterId: getCluster(),
currentcluster: '',
},
mutations: {
// 当前集群
SET_CURRENT_CLUSTERS: (state, data) => {
state.currentcluster = data
},
// 当前集群的id
SET_CLUSTER_ID: (state, data) => {
state.clusterId = data
}
},
actions: {
// 切换集群 params: object currentCluster
SwitchCluster: ({ commit }, currentCluster) => {
commit('SET_CLUSTER_ID', currentCluster.label)
setCluster(currentCluster.label)
commit('SET_CURRENT_CLUSTERS', currentCluster.value)
}
}
}
export default app
2、第二种方法 window.location.reload()
强制熟悉页面、相当于f5,整个页面重新加载,会出现一个瞬间的空白页面,体验不佳
3、第三种方法 this.$router.go(0)
当前页面跳转到当前页面,相当于刷新当前页面,也会出现一个空白页面,体验不佳。
this.$router.go(n):表示页面向前或向后跳转多少个页面,0表示跳转到当前页面。
4、 第四种方法 this.$router.replace
不会出现空白页面。只有地址栏有个快速的切换过程,但是在浏览器的后退不能进行后退了。

浙公网安备 33010602011771号