「Vue」Vue實現無痕刷新

一、什麼是無痕刷新

在不刷新瀏覽器的情況下,實現頁面的刷新。

傳統的刷新頁面方式

<code>window.location.reload()/<code>原生 js 提供的方法

<code>this.$router.go(0)/<code>vue 路由裡面的一種方法

這兩種方法都可以達到頁面刷新的目的,簡單粗暴,但是用戶體驗不好,相當於按 F5 刷新頁面,頁面的重新載入,會有短暫的白屏


二、實現無痕刷新

先在全局組件註冊一個方法,用該方法控制 <code>router-view/<code> 的顯示與否,然後在子組件調用;

用 <code>v-if/<code> 控制 <code><router-view>/<code> 的顯示;

provide:全局註冊方法;

inject:子組件引用 provide 註冊的方法

APP.vue

<template>
<div>
<router-viewv-if="isShow">router-view>
div>
template>
<script>
exportdefault{
name:"App",
provide(){
return{
reload:this.pageReload
}

},
data(){
return{
isShow:true
}
},
methods:{
//刷新
pageReload(){
this.isShow=false;
this.$nextTick(()=>{
this.isShow=true;
})
}
}
};
script>

需要進行無痕刷新的頁面

<template>
<div>
<button@click="handleReload()">點擊刷新button>
div>
template>

<script>
exportdefault{
name:"Home",
inject:["reload"],
methods:{
handleReload(){
this.reload()
}
},
created(){
console.log(111)
}
}
script>

三、provide/inject的使用

簡單的來說就是在父組件中通過provider來提供變量,然後在子組件中通過inject來注入變量(這種方式也可以實現組件傳值,父傳子),provide / inject這對選項需要一起使用,以允許一個祖先組件向其所有子孫後代注入一個依賴,不論組件層次有多深,並在起上下游關係成立的時間裡始終生效。這個東西很類似於React中的context,實現跨組件傳值

  • provide 選項應該是:一個對象或返回一個對象的函數

  • inject 選項應該是:一個字符串數組,或 一個對象,對象的 key 是本地的綁定名

provide

//返回一個對象的函數
<template>
<div>div>
template>
<script>
exportdefault{
name: "App",
provide() {
return{
title: "alley"
};
}
};
script>

//一個對象
<template>
<div>div>
template>
<script>
exportdefault{
name: "App",
provide:{
title:"Alley"
}

};
script>

inject

//一個字符串數組
<template>
<div>
<h2>{{title}}h2>
div>
template>

<script>
exportdefault{
name:"Home",
inject:["title"],
}
script>


//一個對象
<template>
<div>
<h2>{{title}}h2>
div>
template>

<script>
exportdefault{
name:"Home",
inject:{
title:{
type:String,
default:"巷子"
}
},
}
script>

·END·


溫馨提示

如果你喜歡本文,請分享到朋友圈,想要獲得更多信息,請關注我。


分享到:


相關文章: