平時在做項目的過程鍾時常需要刷新組件,這里抽空總結下vue刷新組件的方式
vue刷新組件的方式:
1.給組件不同的key值,這樣每次進入頁面時,當key發生變化時,會釋放原有組件重新加載改組件,這也是我平時最常用的方式
<group :key="new Date().getTime()"> <datetime title="請選擇時間" v-model="time" format="YYYY-MM-DD" :start-date="start" :end-date="end" year-row="{value}年" month-row="{value}月" day-row="{value}日" confirm-text="完成" cancel-text="取消" ></datetime> </group>
2.使用v-if刷新子組件,使用v-if控制改組件的顯示隱藏,當點擊刷新按鈕時,組件需要重新顯示,當v-if里的值發生改變時,組件會重新渲染,來達到強制刷新組件的方式
<button v-if="btnShow" ></button>
// 先將this.btnShow 設為false,再設為true
this.btnShow = false
this.$nextTick(() => (this.btnShow = true))
3.使用組件內置$forceUpdate方法,使用前需要在配置中啟用
import Vue from 'vue'
Vue.forceUpdate() 然后在組件在使用 this.$forceUpdate()
4.刷新整個頁面:this.router.go(0)
5.動態組件 mcake-h5分類切換 【測試成功】
<template> <div> <div class="pro-top" ref='tabs'> <ul class="clearfix"> <li :class='{on:navName=="cakeList"}' @click='routes("cakeList",1)'>蛋糕</li> <li :class='{on:navName=="breadList"}' @click='routes("breadList",11)'>面包</li> <li :class='{on:navName=="snackList"}' @click='routes("snackList",6)'>小食</li> <li :class='{on:navName=="peijianList"}' @click='routes("peijianList",5)'>配件</li> </ul> </div> <div class="pro-main"> <keep-alive> <component :is="navName" :id='id' :isChangeList='isChangeList' :clear='clear' :isRefresh='isRefresh'></component> </keep-alive> <!-- <cakeList :id='id' :isChangeList='isChangeList' :clear='clear' :isRefresh='isRefresh'></cakeList> --> </div> </div> </template> <script> import cakeList from '../components/cake_list' import breadList from '../components/bread_list' import snackList from '../components/snack_list' import peijianList from '../components/peijian_list' export default { name: 'cake', components: { cakeList, breadList, snackList, peijianList }, data () { return { id: 1, isRefresh: false, prolist: [], navName: 'cakeList', } }, props: ['isChangeList', 'clear'], methods:{ routes:function(type,index){ this.navName = type; this.id = index; console.log(index) } } } </script> <style scoped> .pro-top { position: fixed; width: 100%; z-index: 99; padding: 0; top: 1.6rem; background-color: #fff; padding: 0 0.2rem; overflow-x: scroll; -webkit-overflow-scrolling: touch; border-bottom: 0.5px #b7b7b7 solid; } .pro-top ul { display: flex; height:1rem; overflow-x: scroll; overflow-y: hidden; -webkit-overflow-scrolling: touch; } .pro-top ul li { flex: 1; height: 0.5rem; line-height: 0.5rem; margin: 0.2rem 0; font-size: 0.4rem; color: #c5c5c5; border-right: 0.5px #b7b7b7 solid; } .pro-top ul li:last-child{ border: none; } .pro-top ul li.on { position: relative; color: #000; } .pro-main{ margin-top: 1rem; } </style>