Vue-router插件使用

前端开发 作者: 2024-08-20 10:05:01
单页面原理 Vue是单页面开发,即页面不刷新。 页面不刷新,而又要根据用户选择完成内容的更新该怎么做?Vue中采用锚点来完成。 如访问http://127.0.0.1#/index就是主页,而访问ht

单页面原理

Vue-router

示例演示

<body>

<div id="app">
    <router-view></router-view>
</div>

<script src="./vue.js"></script>
<script src="./vue-router.js"></script>
<script>
    // 第一步:书写组件
    const index = {
        template: `
        <div>
            <h1>欢迎访问主页</h1>
            <router-link to="/settings">设置</router-link>
            <router-link to="/backend">后台</router-link>
        </div>
        `
    }

    const backend = {
        template: `
        <div>
            <h1>欢迎访问后台</h1>
            <router-link to="/">访问主页</router-link>
        </div>
        `
    }

    const settings = {
        template: `
        <div>
            <h1>欢迎访问个人设置页面</h1>
            <router-link to="/">访问主页</router-link>
        </div>
        `
    }

    // 第二步:配置路由
    // 根据资源请求来展示或隐藏对应的组件
    const routes = [
        // 主页,/
        {path: "/",component: index},{path: "/backend",component: backend},{path: "/settings",component: settings},]

    // 第三步:实例化路由对象
    // {routes:routes}
    const router = new VueRouter({routes,})

    // 第四步:根组件中添加路由信息
    // {router:router}
    const app = new Vue({
        el: "#app",router,})
</script>
</body>

参数相关

#/book/2
{path: "/book/:id(\\d+)",component: book},// 转义 \d+

我该如何从Template里拿到参数:{{ $route.params }}

我该如何从Methods里拿到参数:this.$route.params
<body>

<div id="app">
    <router-view></router-view>
</div>

<script src="./vue.js"></script>
<script src="./vue-router.js"></script>
<script>
    // 第一步:书写组件
    const index = {
        template: `
          <div>
              <h1>主页</h1>
              <input type="text" v-model="book_id" placeholder="输入要查询的图书编号">
              <router-link :to="'/book/'+book_id">查询图书</router-link>
          </div>
        `,data() {
            return {
                book_id: 0,};
        }
    }

    const book = {
        // 在模板以及方法中,你都可以拿到查询的参数
        template: `
          <div>
              <p>我该如何从Template里拿到参数:{{ $route.params }}</p>
              <p>我该如何从Methods里拿到参数:{{ show() }}</p>
              <p v-for="item in books" v-if="item.id==$route.params.id">你查询的图书是:{{ item }}</p>
          </div>
        `,data() {
            return {
                books: [
                    {id: 1,name: "红楼梦",author: "曹雪芹",price: 199,},{id: 2,name: "西游记",author: "吴承恩",price: 179,{id: 3,name: "三国演义",author: "罗贯中",price: 158,{id: 4,name: "水浒传",author: "施耐庵",price: 128,]
            }
        },methods:{
            show(){
                return this.$route.params
            }
        }
    }

    // 第二步:配置路由
    const routes = [
        // 主页,/
        {path: "/",{path: "/book/:id(\\d+)",// 转义 \d+
    ]

    // 第三步:实例化路由对象
    // {routes:routes}
    const router = new VueRouter({routes,})
</script>
</body>
{path: "/book/:id?",// ?代表可以有也可以没有
<body>

<div id="app">
    <router-view></router-view>
</div>

<!--查询模板-->
<template id="result">
    <div>
        <table border="1" :style="{borderCollapse:'collapse'}">
            <caption :style="{border:'1px solid #000',fontSize:'1.2rem'}">查询结果</caption>
            <thead>
            <tr>
                <th>编号</th>
                <th>名称</th>
                <th>作者</th>
                <th>价格</th>
            </tr>
            </thead>
            
            <!-- 查询一本 -->
            <tbody v-if="$route.params.id">
            <tr v-for="item in books" v-if="item.id == $route.params.id">
                <td>{{ item.id }}</td>
                <td>{{ item.name }}</td>
                <td>{{ item.author }}</td>
                <td>{{ item.price }}</td>
            </tr>
            </tbody>
            
            <!-- 查询所有 -->
            <tbody v-else>
            <tr v-for="item in books">
                <td>{{ item.id }}</td>
                <td>{{ item.name }}</td>
                <td>{{ item.author }}</td>
                <td>{{ item.price }}</td>
            </tr>
            </tbody>
        </table>
    </div>
</template>

<script src="./vue.js"></script>
<script src="./vue-router.js"></script>
<script>
    // 第一步:书写组件
    const index = {
        template: `
          <div>
          <h1>主页</h1>
          <input type="text" v-model="book_id" placeholder="输入要查询的图书编号">
          <router-link :to="'/book/'+book_id">查询单个图书</router-link>
          <router-link to="/book/">查询所有图书</router-link>
          </div>
        `,};
        }
    }

    const book = {
        // 在模板以及方法中,你都可以拿到查询的参数
        template: `#result`,}

    // 第二步:配置路由
    const routes = [
        // 主页,/
        {path: "/",{path: "/book/:id?",// 转义 \d+,?可以有也可以没有
    ]

    // 第三步:实例化路由对象
    // {routes:routes}
    const router = new VueRouter({routes,})
    
</script>
</body>

路由别名

    const routes = [
        {path: "/",component: index,name: "index"},component: book,name: "query_book"},]
<!-- 有参数就传递,没有就不传递。注意在to前添加: -->
<router-link :to="{name:'query_book',params:{id:书籍编号}}">查询</router-link>
// 模板中的按钮
<button @click="func(书籍编号)">查看详情</button>

// js
func(bookId){
	// 使用url拼接跳转
    let url = {path:"/book/"+bookId};
    // 使用别名进行跳转跳转:
    // {name:'book_query',params:{id:id}}
    this.$router.push(url);  // 使用$router.push(url)进行跳转
}

视图布局

<div id="app">
	<!-- 第一层,展示学校 -->
    <router-view></router-view>
</div>

# 子组件中的关键代码
 <router-view></router-view>
 
# 路由中的代码,第一层的路由匹配第一层的router-view,第二层的路由就在第二层的router-view中显示
 path: "/school",component: school,name: "school",children: [
     {path: "/school/teacher",component: teacher,name: "teacher"},{path: "/school/classes",component: classes,name: "classes"},]
<body>

<div id="app">
	<!-- 第一层,展示学校 -->
    <router-view></router-view>
</div>


<script src="./vue.js"></script>
<script src="./vue-router.js"></script>
<script>
    // 第一步:书写组件
    const school = {
        template: `
        <div>
            <h1>欢迎来到大肥羊学校</h1>
            <router-link :to="{name:'classes'}">查看班级</router-link>
            <router-link :to="{name:'teacher'}">查看老师</router-link>
            <!-- 第二层,展示班级或者教师 -->
            <router-view></router-view>
        </div>
        `
    }

    const teacher = {
        template: `
          <div>
            <ul>
              <li v-for="item in teacherMessage">{{item.id}}-{{item.name}}</li>
            </ul>
          </div>
        `,data() {
            return {
                teacherMessage: [
                    {id: 1,name: "王老师",name: "张老师",name: "李老师",]
            }
        }
    }


    const classes = {
        template: `
          <div>
              <ul>
                <li v-for="item in classMessage">{{item.id}}-{{item.name}}</li>
              </ul>
          </div>
        `,data() {
            return {
                classMessage: [
                    {id: 1,name: "一年级一班",name: "一年级二班",name: "一年级三班",]
            }
        }
    }

    // 第二步:配置路由
    const routes = [
        {
            path: "/school",children: [
                {path: "/school/teacher",]
        },})

</script>
</body>
<body>

<div id="app">
    <router-view></router-view>
</div>

<script src="./vue.js"></script>
<script src="./vue-router.js"></script>
<script>

    // 假设是从后端抓取数据
    let schoolTitle = "欢迎来到大肥羊学校";

    // 5s后发生改变
    setTimeout(() => {
        schoolTitle = "欢迎来到小肥羊学校";
    },5000);

    // 第一步:书写组件
    const school = {
        template: `
        <div>
            <h1>{{ title }}</h1>
            <router-link :to="{name:'classes'}">查看班级</router-link>
            <router-link :to="{name:'teacher'}">查看老师</router-link>
            <p><button @click="updateTitle">更新新的标语</button></p>
            <router-view></router-view>
        </div>
        `,data(){
            return {
                title : "",}
        },created(){
            // 假设发送异步请求
            console.log("school钩子函数触发了...")
            this.title = schoolTitle;
        },methods:{
            updateTitle(){
                this.title = schoolTitle;
            }
        }
    }

    const teacher = {
        template: `
          <div>
            <h3>老师太多了,显示不过来...</h3>
          </div>
        `,}


    const classes = {
        template: `
          <div>
            <h3>班级太多了,显示不过来...</h3>
          </div>
        `,}

    // 第二步:配置路由
    const routes = [
        {
            path: "/school",})

</script>
</body>
    const school = {
		template:"...",created(){
            // 假设发送异步请求
            this.getTitle();
        },methods:{
            getTitle(){
                // 从后端获取数据
                this.title = schoolTitle;
            }
        },watch:{
            $route(to,from){
                // to 要跳转的页面
                // from 从那个页面进行跳转
                this.getTitle();
            }
        }
    }
    // 第一步:书写组件
    const school = {
    	template:"...",beforeRouteUpdate (to,from,next) {
            this.getTitle();
        }
    }
# 根组件模板
<div id="app">
    <!-- 这里只放个人主页 -->
    <router-view></router-view>
    <router-view name="menu"></router-view>
    <router-view name="show"></router-view>
</div>
   

# Js配置路由,/代表根目录。有三个视图,router-view
path: "/",components: {
    default: header,// 如果 view-router没有name属性,则用default
    menu: menu,show: show,}
 <style>
        *{
            padding: 0;
            margin: 0;
            box-sizing: border-box;
        }
        header{
            height: 45px;
            display: flex;
            justify-content: space-evenly;
            background-color: #ddd;
            align-items: center;
        }
        body>div>div:nth-child(2){
            display: inline-flex;
            width: 15%;
            border: 1px solid #ddd;
            height: 1000px;
        }
        menu>ul{
            list-style-type: none;
            display: inline-flex;
            flex-flow: column;
            
        }
        menu>ul>li{
            margin: 10px 0 0 10px;
        }
        body>div>div:last-child{
            display: inline-flex;
            justify-content: center;
            border: 1px solid #ddd;
            width: 70%;
            height: 1000px;
        }

    </style>

<body>
    <div id="app">
        <!-- 这里只放个人主页 -->
        <router-view></router-view>
        <router-view name="menu"></router-view>
        <router-view name="show"></router-view>
    </div>
   
    <!-- 头部组件 -->
    <template id="header">
        <div>
            <header><span>首页</span><span>新闻</span><span>关注</span><span>链接</span></header>
        </div>
    </template>

    <!-- 左侧菜单 -->
    <template id="menu">
        <div>
            <menu>
                <ul>
                    <li>最新</li>
                    <li>最热</li>
                    <li>最多评论</li>
                </ul>
            </menu>
        </div>
    </template>

    <!-- 内容区域 -->
    <template id="show">
        <div>
            <section>
                <h1>内容区域</h1>
            </section>
        </div>
    </template>

    <script src="vue.js"></script>
    <script src="vue-router.js"></script>
    <script>

        // 第一步:书写组件
        const header = {
            template: "#header",}

        const menu = {
            template: "#menu",}

        const show = {
            template: "#show",}

        // 第二步:配置路由
        const routes = [
            {
                // 当你访问主页时,有三个组件扁平显示
                path: "/",components: {
                    default: header,// 如果 view-router没有name属性,则用default
                    menu: menu,}
            }

        ]

        // 第三步:实例化路由对象
        const router = new VueRouter({
            routes,// es6新语法
        })


        // 第四步:根组件中添加路由信息 
        const app = new Vue({
            el: "#app",});

    </script>
</body>

重定向

const routes = [
    // 当用户访问doc时,将会跳转到help中,地址栏中显示是help
    { path: "/help",component: help,name: "help"},{ path: "/doc",redirect: { name: "help" } }
]
const routes = [
    // 用户输入在alias中的所有路径,都会交给help组件进行处理
    { path: "/help",name: "help",alias: ["/doc","/doc.html","/help.html"] },]

history模式

切换动画

        // 书写组件
        const index = {
            template:
             `
            <transition enter-active-class="animate__animated  animate__bounce">
                <h1>wecome to index</h1>
            </transition>
            `,}

        const backend = {
            template:             `
            <transition enter-active-class="animate__animated  animate__bounce">
                <h1>wecome to backend</h1>
            </transition>
            `,}
原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_65455.html
Vue-router插件使用