vue-router组件

vue + vue-router组件 可以实现 SPA(single Page Application),即:单页面应用

单页面应用,简而言之就是项目只有一个页面。

一个页面如何呈现多种界面的效果呢?

  • 基于vue开发多个组件,例如:活动组件、课程组件、咨询组件
  • 在页面上 vue-router 用来管理这些组件,用户点击某个按钮,就显示特定的组件(数据基于Ajax获取)。

1 下载和引用

官方地址:https://router.vuejs.org/zh/

下载地址:https://unpkg.com/vue-router@4

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <!--  vue-router.js 依赖 vue.js -->
    <script src="vue.js"></script>
    <script src="vue-router.js"></script>
    
</head>
<body>
	...
</body>
</html>

注意:后期用脚手架开发时,可以直接使用npm下载和引用。

2 快速上手

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body {
            margin: 0;
        }

        .container {
            width: 980px;
            margin: 0 auto;
        }

        .menu {
            height: 48px;
            background-color: #499ef3;
            line-height: 48px;

        }

        .menu a {
            color: white;
            text-decoration: none;
            padding: 0 10px;
        }
    </style>

    <script src="vue.js"></script>
    <script src="vue-router.js"></script>
</head>
<body>
<div id="app">
    <div class="menu">
        <div class="container">
            <router-link to="/">Logo</router-link>
            <router-link to="/home">首页</router-link>
            <router-link to="/course">课程</router-link>
            <router-link to="/news">资讯</router-link>
        </div>
    </div>
    <div class="container">
        <router-view></router-view>
    </div>

</div>

<script>

    const Home = {template: '<div>首页内容...</div>'}
    const Course = {template: '<div>课程内容..</div>'}
    const News = {template: '<div>资讯内容..</div>'}

    const router = new VueRouter({
        routes: [
            { 
                path: '/', 
                component: Home
            },
            {
                path: '/home', 
                component: Home
            },
            {path: '/course', component: Course},
            {path: '/news', component: News}
        ],
    })

    var app = new Vue({
        el: '#app',
        data: {
            name: "武沛齐",
        },
        methods: {},
        router: router
    })
</script>
</body>
</html>
posted @ 2022-08-07 22:03  下个ID见  阅读(68)  评论(0)    收藏  举报