【发布时间】:2021-05-02 20:08:31
【问题描述】:
我有一个类似于模式的侧边栏组件。单击按钮时,侧边栏将转换为带有导航链接的视口。这些导航链接实际上是连接到 vue-router 的路由器链接。
我想要完成的事情
当我单击侧边栏组件内的路由链接时,我希望侧边栏从视口过渡,并且我希望单击的路由链接的组件在不重新加载页面的情况下呈现。
目前正在发生的事情
当我单击路由器链接时,侧边栏会立即从 DOM 中删除。它不会按预期翻译出屏幕。此外,页面会重新加载。
我还尝试了什么
我还尝试将 <transition> 包装器连同关联的 CSS 类一起移动到 TheSidebar.vue 组件中,并将 sidebarIsVisible 作为道具从 App.vue 传递到 TheSidebar.vue。
我的代码
可以在here找到 Codesandbox 演示
App.vue
<template>
<router-view></router-view>
<button @click="toggleSidebar" class="toggleBtn">Toggle Sidebar</button>
<transition name="sidebar">
<the-sidebar
v-if="sidebarIsVisible"
@link-clicked="toggleSidebar"
></the-sidebar>
</transition>
</template>
<script>
import TheSidebar from "./components/TheSidebar.vue";
export default {
components: {
TheSidebar,
},
data() {
return {
sidebarIsVisible: false,
};
},
methods: {
toggleSidebar() {
this.sidebarIsVisible = !this.sidebarIsVisible;
},
closeSidebar() {
this.sidebarIsVisible = false;
},
},
};
</script>
<style>
/* basic styling */
.toggleBtn {
position: fixed;
top: 5px;
left: 5px;
}
.sidebar-enter-active {
animation: slide-sidebar 0.3s ease;
}
.sidebar-leave-active {
animation: slide-sidebar 0.3s ease reverse;
}
@keyframes slide-sidebar {
from {
transform: translateX(-100%);
}
to {
transform: translateX(0);
}
}
</style>
TheSidebar.vue
<template>
<div class="sidebar">
<nav>
<ul>
<li>
<router-link @click="$emit('link-clicked')" to="/link1">
Link 1
</router-link>
</li>
<li>
<router-link @click="$emit('link-clicked')" to="/link2">
Link 2
</router-link>
</li>
</ul>
</nav>
</div>
</template>
<script>
export default {
emits: ["link-clicked"],
};
</script>
<style scoped>
/* basic styling */
</style>
main.js
import { createApp } from "vue";
import { createRouter, createWebHistory } from "vue-router";
import App from "./App.vue";
import LinkOne from "./components/LinkOne.vue";
import LinkTwo from "./components/LinkTwo.vue";
const app = createApp(App);
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: "/link1", component: LinkOne },
{ path: "/link2", component: LinkTwo }
]
});
app.use(router);
app.mount("#app");
【问题讨论】:
标签: javascript html vue.js vue-component vue-router