我创建了一个vuejs3单页应用程序"路由器和路由也没有"url";更改(希望始终在地址栏显示主页)但需要帮助,以正确的方式去做。
我想
- 有一个主html页面,页面上有链接,按钮等,即在运行时间页归档(如何??)
- 的起始页被第一个主页 填充
- 点击每个链接或按钮,在页面 中选择要替换的组件
index . html页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + Vue</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>
main.js
import { createApp } from 'vue'
import App from './App.vue'
import store from './store'
import './style.css'
const app = createApp(App)
app.use(store)
app.mount('#app')
应用程序。vue文件
<template>
<div>
<h1>Hello world</h1>
<button type="button" @click="changeView(0)"> Home 1 </button>
<button type="button" @click="changeView(1)"> Home 2 </button>
<button type="button" @click="changeView(2)"> Home 3 </button>
</div>
<Suspense v-if="isLoggedIn">
<template #default>
<changeViews />
</template>
<template #fallback>
<p>loading...</p>
</template>
</Suspense>
<changeViews v-if="showIt" />
</template>
<script setup>
import { defineAsyncComponent, ref, markRaw } from 'vue'
const menus = [
{
name: "home"
,url: "home"
},
{
name: "about"
,url: "about"
},
{
name: "contact"
,url: "contact"
},
]
let showIt = ref(false)
let changeViews = ref(null)
changeViews.value = markRaw(defineAsyncComponent((loc) =>
import(`./components/${menus[0].url}/index.vue`)
))
function changeView(ja){
showIt.value = false
if(ja===1) {
showIt.value = true
changeViews.value = defineAsyncComponent((loc) =>
import(`./components/${menus[ja].url}/index.vue`)
)
}
}
</script>
页面(home, about, contact)非常简单:
<template>
<h2> Home </h2>
<div class="card">
<button type="button" @click="count++">count is {{ count }}</button>
<button type="button" @click="count++">count is {{ count }}</button>
<button type="button" @click="count++">count is {{ count }}</button>
</div>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
const count = ref(0)
</script>
它正在工作,但是看起来很乱,我不知道如何以一种好的方式来做。
我已经搜索过了,但是每个地方都在谈论如何使用路由,而我想避免路由和没有url更改
我认为你需要使用动态组件。你可以动态地指定在一个地方呈现哪个组件。
<template>
<component :is="currentPage" />
</template>
<script setup>
import PageA from '@/components/PageA.vue'
import PageB from '@/components/PageB.vue'
import PageC from '@/components/PageC.vue'
const currentPage = ref('PageA')
function changeView(page) {
currentPage.value = page
}
</script>