vue 3.x vue-router使用

2021/6/21 6:26:18

本文主要是介绍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使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程