其他分享
首页 > 其他分享> > vue 3.x vue-router使用

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,import,App,使用,Component1,Component2,router
来源: https://www.cnblogs.com/hu308830232/p/14910582.html