踩坑记录

86 阅读1分钟

keepalive

使用watch监听route,当路由发生变化的时候,把需要缓存的组件name,添加到include数据中

<router-view v-slot="{ Component }">
    <keep-alive :include="includeList">
      <component :is="Component"></component>
    </keep-alive>
</router-view>
          
export default defineComponent({
  components: { Header, SideMenu, Footer, AppBreadCrumbs },
  setup() {
    const route = useRoute()
    const includeList = ref([] as any[])
    const router = useRouter()
    // 踩坑:刷新缓存页面后,没有监听到route变化导致当前页面无法缓存数据
    // watch(route, (to: any) => {
    //   if (to.meta.keepAlive && includeList.value.indexOf(to.name) === -1) {
    //     includeList.value.push(to.name)
    //   }
    // })
    
     // 解决:添加{ immediate: true }即可,刷新页面后立即监听route
     watch(route, (to: any) => {
       if (to.meta.keepAlive && includeList.value.indexOf(to.name) === -1) {
         includeList.value.push(to.name)
       }
     },{ immediate: true })
    return { includeList }
  },
})
</script>

vue3中provide inject用法踩坑

A页面
const loading = ref(false)
const readOnly = ref(false)


provide(
  'provideState',
    {
        loading,
        readOnly,
    }
 })
)

B页面
// 在页面中必须通过.value才能取到正确的值
<el-select placeholder="请选择" v-model="formData.serviceType" :disabled="state.readOnly.value">
  <el-option label="专家" :value="1" />
</el-select>

const state = inject('provideState')

后面就不理解为什么必须加value才能取到正确的值,仔细查看文档才找到答案

image.png

最后的方案建议一个个传递,或把多个变量封装到一个ref中

const state = ref({
    loading: false
    readOnly: false
})
provide('provideState', state})


const loading = ref(false)
const readOnly = ref(false)
provide('loading', loading})
provide('readOnly', readOnly})