今天就跟大家聊聊有关怎么在vue中实现主动刷新,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
1.window.location.reload(),是原生JS提供的方法,this.$router.go(0):是vue路由里面的一种方法,这两种方法都可以达到页面刷新的目的,简单粗暴,但是用户体验不好,相当于按F5刷新页面,会有短暂的白屏,相当于页面的重新载入。
2.通过路由跳转的方法刷新,具体思路是点击按钮跳转一个空白页,然后再马上跳回来:
当前页面:
<template>
<div>
<el-button type="primary" class="btn" @click="btnaction">摁我刷新页面</el-button>
</div>
</template>
<script>
export default{
data(){
return{
}
},
mounted(){
},
methods:{
btnaction() {
// location.reload()
// this.$router.go(0)
this.$router.replace({
path:'/empty',
name:'empty'
})
}
}
}
</script>
空白页面:
<template>
<h2>
空页面
</h2>
</template>
<script>
export default{
data() {
return{
}
},
created(){
this.$router.replace({
path:'/',
name:'father'
})
}
}
</script>
当点击按钮时地址栏会有快速的地址切换过程。
3.控制<router-view></router-view>的显示与否,在全局组件注册一个方法,该方法控制router-view的显示与否,在子组件调用即可:
APP.vue
<template>
<div id="app">
<router-view v-if="isRouterAlive"></router-view>
</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
console.log('reload')
})
}
}
}
</script>
当前组件:
<template>
<div>
<el-button type="primary" class="btn" @click="btnaction">摁我刷新页面</el-button>
</div>
</template>
<script>
export default{
inject: ['reload'], // 引入方法
data(){
return{
}
},
components:{
},
mounted(){
},
methods:{
btnaction() {
// location.reload()
// this.$router.go(0)
// this.$router.replace({
// path:'/empty',
// name:'empty'
// })
this.reload() // 调用方法
}
}
}
</script>
为什么要使用Vue
Vue是一款友好的、多用途且高性能的JavaScript框架,使用vue可以创建可维护性和可测试性更强的代码库,Vue允许可以将一个网页分割成可复用的组件,每个组件都包含属于自己的HTML、CSS、JavaScript,以用来渲染网页中相应的地方,所以越来越多的前端开发者使用vue。
看完上述内容,你们对怎么在vue中实现主动刷新有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注天达云行业资讯频道,感谢大家的支持。