我是靠谱客的博主 鲜艳眼睛,最近开发中收集的这篇文章主要介绍Vue中的路由使用及添加参数,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

  • 在一个系统中会由很多页面组成,在Vue开发中这些页面通常使用的是Vue中的组件来实现的,那么当在一个页面要跳转到另外一个页面的时候是通过改变url路径来实现的,那么这个时候Vue需要知道当前url对应的是哪个组件页面
<!DOCTYPE html>
<html lang="en">

<head>
    <title></title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="./vue2.js"></script>
    <!-- 引入路由文件 -->
    <script src="./vue-router.js"></script>
</head>

<body>
    <div id="app">
        <ul>
            <!-- 
          vue路由中通过router-link去做跳转,它有一个to属性,to属性的值必须和path中的路径对应
          router-link将来会被渲染成为a标签,它的to属性会被渲染成a标签的href属性,但它的值前对面会加一个#,变为锚点
        -->
            <li>
                <router-link to="/index">首页</router-link>
            </li>
            <li>
                <router-link to="/productType/11">蔬菜</router-link>
            </li>
            <li>
                <router-link to="/productType/22">水果</router-link>
            </li>
            <li>
                <router-link to="/productType/33">肉类</router-link>
            </li>
        </ul>
        <!--6. 通过router-view挖坑,路径匹配到的组件都会渲染到这个坑里面来  -->
        <router-view></router-view>
    </div>

    <script>
        //2.准备路由需要的组件
        var index = Vue.component('indexA', {
            template: `<div>这是首页</div>`
        })
        var productType = Vue.component('indexB', {
                // 在html中获取路由参数 通过$route.params.参数名
                template: `<div>这是显示商品编号{{$route.params.id}}</div>`,
                mounted() {
                    // 在js中获取路由参数 通过this.$route.params.参数名
                    console.log(this.$route.params.id);
                    console.log(this.$route);
                }
            })
            //3.创建路由对象在这个对象里面去配置路由规则
        var router = new VueRouter({
            // 4. 通过routes属性配置路由规则,它是一个数组,数组中放的是对象,每个对象对应一条规则,并且每个对象里面都包含有name(表示路由规则的名称)/path(表示路径)/component(表示路径对应的组件)
            routes: [{
                name: 'indexA',
                component: index,
                path: '/index'
            }, {
                name: 'productType',
                component: productType,
                path: '/productType/:id' //路由加参数方法  :参数名
            }]
        })
        var vm = new Vue({
            el: '#app',
            // 5. 在vue实例中注入路由,这样整个应用程序都会拥有路由了
            router,
            data: {

            }
        })
    </script>
</body>

</html>

最后

以上就是鲜艳眼睛为你收集整理的Vue中的路由使用及添加参数的全部内容,希望文章能够帮你解决Vue中的路由使用及添加参数所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(63)

评论列表共有 0 条评论

立即
投稿
返回
顶部