• 首页
  • 发布文章
  • 我的文章
  • 我的收藏
  • 设置
  • 退出

Vue中常使用的三种刷新页面的方式_vue2刷新页面

blmius 2023-08-04 16:35:38
收藏
编辑
上架
下架

一、通过js原始方法刷新

缺点: 出现闪白

<template>
  <div>
      <div class="header">
          <button @click="update()">刷新页面</button>
      </div>
  </div>
</template>

<script>
export default {
    methods:{
        update(){
            location.reload()
        }
    }
}
</script>

二、通过Vue自带的路由进行跳转

缺点: 出现闪白

<template>
    <div>
        <div class="header">
            <button @click="update()">刷新页面</button>
        </div>
    </div>
</template>

<script>
export default {
    methods:{
        update(){
            this.$router.go(0)
        }
    }
}
</script>

三、通过在APP页面进行demo进行刷新(推荐)

优点: 不闪白

1.vue2写法

(1)、在APP页面中写入下面代码

<template>
    <div id="app">
        <router-view v-if="isShow"/>
    </div>
</template>

<script>
export default {
    name: 'App',
    provide(){
        return{
            reload:this.reload
        }
    },
    data(){
        return{
            isShow:true
        }
    },
    methods:{
        reload(){
            this.isShow=false;
            this.$nextTick(()=>{
                this.isShow=true
            })
        }
   }
}
</script>

(2)、在需要刷新的页面进行引入并使用

<template>
    <div>
        <div class="header">
            <button @click="update()">刷新页面</button>
        </div>
    </div>
</template>

<script>
export default {
    inject:[
        'reload'
    ],
    methods:{
        update(){
            this.reload()
            console.log('刷新页面')
        }
    }
}
</script>

2. vue3.2写法

(1)、在APP页面中写入下面代码

<template>
    <router-view v-if="isRouter" />
</template>

<script setup>
import { nextTick, provide, ref } from "Vue"
const isRouter = ref(true)
const reload = () => {
    isRouter.value = false
    nextTick(() => {
        isRouter.value = true
    })
}
provide("reload", reload)
</script>

(2)、在需要刷新的页面进行引入并使用

<script setup>
import { inject } from 'vue'
const reload = inject("reload")
// 刷新页面
const onSubmitForm = () => {
    reload()
}
</script>

本文转自 https://blog.csdn.net/qq_52421092/article/details/129651914,如有侵权,请联系删除。