Vue路由简单使用

时间:2020-05-01

安装插件

npm install vue-router --save

建立组件代码

Son1.vue

<template>
    <div>
        <h3>son1</h3>
    </div>
</template>

<script>
    export default {
        name: "Son1",
        data: function () {
            return {
                'msg': ''
            };
        }
    }
</script>

<style scoped>

</style>

Son2.vue

<template>
    <div>
        <h3>son2</h3>
        <p>

        </p>
    </div>
</template>

<script>
    export default {
        name: "Son2"
    }
</script>

<style scoped>

</style>

建立路由文件

app.js

import VueRouter from 'vue-router';
import Son1 from "../components/Son1";
import Son2 from "../components/Son2";
import Vue from "vue";
Vue.use(VueRouter);
export default new VueRouter({
    routes:[
        {
            path:'/',
            redirect:'/son1'
        },
        {
            path:'/son1',
            component:Son1
        },
        {
            path:'/son2',
            component:Son2
        }
    ]
});

编写父组件代码

App.vue

<template>
    <div id="app">
        <h2 slot="title">父组件</h2>
        <div>
            <router-link to="/son1">son1</router-link>
            <router-link to="/son2">son2</router-link>
        </div>
        <div>
            <router-view></router-view>
        </div>
    </div>
</template>

<script>

    export default {
        name: 'App',
        components: {
        },
        methods: {},
        data: function () {
            return {
                'msg': ''
            };
        }
    }
</script>

<style>

</style>

修改main.js代码

import Vue from 'vue'
import App from './App.vue'
import router from './router/app';
Vue.config.productionTip = false;

new Vue({
  render: h => h(App),
  router
}).$mount('#app');