标题描述的可能不太好,请看下面 demo
router.js
const routes = [ { path: '/board/:boardId', component: board } ] app.vue
<template> <router-link to="/board/1">画板 1</router-link> <router-link to="/board/2">画板 2</router-link> <router-view /> </template> board.vue
<template> <div>画板 {{ $route.params.boardId }}</div> <button @click="addP">添加一个段落</button> <div class="container"></div> </template> <script setup> function addP() { let p = document.createElement('P') p.innerText = '新增内容' document.querySelector('.container').appendChild(p) } </script> 大概就是有两个画板,点击按钮就会切换画板,画板都是由 board 组件复用生成的,在画板中可以添加文本
我需要的功能是两个画板互不影响,在画板 1 中添加文字后,切换到画板 2 ,画板 2 上是没有画板 1 中文字
即下图中效果:

但实际的效果:

原因我也知道,复用组件生成的页面之间切换,代码不会重复执行
那怎样才能保持两个画板的独立呢?
之前请教的一个问题中,@vinsony 老哥提供了一种绑定 key 的思路
我改了下 demo 中 app.vue 实现了预定的效果
<template> <router-link to="/board/1">画板 1</router-link> <router-link to="/board/2">画板 2</router-link> <router-view v-slot="{ Component, route }"> <keep-alive> <component :is="Component" :key='route.fullPath'/> </keep-alive> </router-view> </template> 但是 @Zzzz77 老哥说绑定 key 这种骚操作有点野路子,那不绑定 key 怎么解决这个问题呢?
