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
不會出現空白頁面。只有地址欄有個快速的切換過程,但是在瀏覽器的后退不能進行后退了。
