vue 3.x vue-router使用
Posted 天行子
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vue 3.x vue-router使用相关的知识,希望对你有一定的参考价值。
vue-router安装
npm install vue-router@4 --save-dev
vue-router使用
router.js
import { createRouter, createWebHistory } from \'vue-router\'
import Component1 from "./components/Component1"
import Component2 from "./components/Component2"
/**
* 创建路由对象
*/
const routes = [
{ path: \'/Component1\', component: Component1 },
{ path: \'/Component2\', component: Component2 },
];
//创建路由
const router = createRouter({
history: createWebHistory(),
routes,//定义的路由
});
export default router;
main.js
import { createApp } from \'vue\'
import App from \'./App.vue\'
import router from \'./router.js\'
createApp(App).use(router).mount(\'#app\');
App.vue
<template>
<div id="app">
<div>
<router-link to="/Component1">组件1</router-link>
<router-link to="/Component2">组件2</router-link>
</div>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: \'App\'
}
</script>
<style>
#app{
text-align: center;
}
a {
margin: 10px;
}
</style>
components/Component1.vue
<template>
<div>
<h3>我是组件1</h3>
<p>{{title}}</p>
</div>
</template>
<script>
export default {
name: "Component1",
data(){
return {
title: \'组件1title\'
}
}
}
</script>
<style scoped>
</style>
components/Component2.vue
<template>
<div>
<h3>我是组件2</h3>
<p>{{title}}</p>
</div>
</template>
<script>
export default {
name: "Component2",
data(){
return {
title: \'组件2title\'
}
}
}
</script>
<style scoped>
</style>
刷新浏览器看效果
以上是关于vue 3.x vue-router使用的主要内容,如果未能解决你的问题,请参考以下文章
Vue3.0全家桶最全入门指南 - vue-router@4.x和vuex@4.x (3/4)