vue刷新當(dāng)前頁面有挺多種方法,比如
window.location.reload()
或者
this.$router.go(0)
但是這兩種方法是會出現(xiàn)一瞬間的白屏,體驗不好,所以這里給大家推薦第三種比較好用的刷新頁面的方法
在app.vue的<router-view></router-view>加上v-if屬性
<router-view v-if="isRouterAlive"></router-view>
在data里面加上isRouterAlive,當(dāng)然這個屬性名可以自己定義,默認(rèn)值為true
data () {
return {
isRouterAlive: true
}
}
methods里面加入一個刷新的方法
methods: {
reload () {
this.isRouterAlive = false
this.$nextTick(function() {
this.isRouterAlive = true
})
}
}
最后,需要把這個函數(shù) provide 出去
provide () {
return {
reload: this.reload
}
}
這樣,app.vue上就設(shè)置完了
那么當(dāng)我們需要刷新的時候,在需要的頁面上加上這個函數(shù)就可以了
首先注入這個函數(shù)
inject: ['reload']
然后在需要用到這個函數(shù)的地方去引用就行了
refresh () {
this.reload()
}
這樣子就可以刷新頁面了,而且不會出現(xiàn)白屏的情況,比前面兩種方法好用,推薦大家使用。
附帶上完整代碼
<template>
<div id="app">
<div class="wrap">
<router-view v-if="isRouterAlive"></router-view>
</div>
</div>
</template>
<script>
export default {
name: 'App',
provide () {
return {
reload: this.reload
}
},
data () {
return {
isRouterAlive: true
}
},
methods: {
reload () {
this.isRouterAlive = false
this.$nextTick(function() {
this.isRouterAlive = true
})
}
}
}
</script>
<style>
#app{
position: relative;
}
@media only screen and (min-width: 1200px) {
.wrap{
width: 65%;
margin: 0 auto;
}
}
</style>
<template>
<button @click="refresh"></button>
</template>
<script>
export default{
name: 'refresh',
inject: ['reload'],
methods: {
refresh () {
this.reload()
}
}
}
</script>