Vue Routerとは
ゴール
環境構築
npm install -g @vue/cli
vue create example-router
import { createApp } from 'vue';
import App from './App.vue';
const app = createApp(App);
app.mount('#app');
<template>
<div>
<a href="#" @click="setPage('test-page01')">Test Page01</a>
<a href="#" @click="setPage('test-page02')">Test Page02</a>
</div>
<component :is="activePage"></component>
</template>
<script>
import TestPage01 from './components/TestPage01.vue'
import TestPage02 from './components/TestPage02.vue'
export default {
name: 'App',
components: {
TestPage01, TestPage02
},
data() {
return {
activePage: 'test-page01'
}
},
methods: {
setPage(page) {
this.activePage = page;
}
}
}
</script>
<template>
<p>This is Test Page 01</p>
</template>
<template>
<p>This is Test Page 02</p>
</template>
<template>
<div>
<router-link to="/test-page01">Test Page01</router-link>
<router-link to="/test-page02">Test Page02</router-link>
</div>
<router-view></router-view>
</template>
<script>
import TestPage01 from './components/TestPage01.vue'
import TestPage02 from './components/TestPage02.vue'
export default {
name: 'App',
components: {
TestPage01, TestPage02
},
}
</script>
import { createApp } from 'vue';
import App from './App.vue';
import router from './router.js'; // Add
const app = createApp(App);
app.use(router); // Add
app.mount('#app');
import { createRouter, createWebHistory } from 'vue-router';
const router = createRouter({
history: createWebHistory(),
...
});
import TestPage01 from './components/TestPage01.vue';
import TestPage02 from './components/TestPage02.vue';
import NotFound from './components/NotFound.vue';
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', redirect: '/test-page01' },
{ name: 'test1', path: '/test-page01', component: TestPage01 },
{ name: 'test2', path: '/test-page02', component: TestPage02 },
{ path: '/:notFound(.*)', component: NotFound }
],
});
const router = createRouter({
routes: [
...
],
linkActiveClass: 'example-active',
linkExactActiveClass: 'example-exact-active',
});
import { createRouter, createWebHistory } from 'vue-router';
import TestPage01 from './components/TestPage01.vue';
import TestPage02 from './components/TestPage02.vue';
import NotFound from './components/NotFound.vue';
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', redirect: '/test-page01' },
{ name: 'test1', path: '/test-page01', component: TestPage01 },
{ name: 'test2', path: '/test-page02', component: TestPage02 },
{ path: '/:notFound(.*)', component: NotFound }
],
linkActiveClass: 'example-active',
linkExactActiveClass: 'example-exact-active',
});
export default router;