• Vue 路由的基本概念与使用


    Vue 路由 概念与基本使用

    vue-router: vue的一个插件,专门来实现spa应用

    关于spa应用的理解

    单页应用 single page application 整个应用只有一个完整的页面
    点击页面的导航,只会做局部更新
    通过ajax请求数据

    路由的理解

    什么是路由
    一个路由就是一组映射关系 key:value,key为路径,value是function或Component

    前端路由与后端路由

    后端路由
    value是function,用来处理客户端的请求
    即匹配请求路径返回不同的数据

    前端路由
    value是Component,用来展示不同的内容
    即匹配浏览器路径展示不同的Component

    路由的基本使用

    安装

    npm i vue-router
    

    配置routes

    router/index.js

    import VueRouter from 'vue-router'
    import Island from '../components/Island'
    import Polaris from '../components/Polaris'
    
    export default new VueRouter({
        routes:[
            {
                component:Island,
                path:"/Island"
            },
            {
                component:Polaris,
                path:"/Polaris"
            },
        ]
    })
    

    注册插件

    main.js

    import Vue from 'vue'
    import App from './App.vue'
    import VueRouter from 'vue-router'
    import router from './router'
    
    // 关闭Vue的生产提示
    Vue.config.productionTip = false
    
    Vue.use(VueRouter)
    
    // 创建Vue实例
    new Vue({
      // 将app组件放入容器中
      render: h => h(App),
      router
    }).$mount('#app')
    

    页面使用

    router-link:

    • active-class 配置激活的路由样式
    • to 点击之后要修改的路径

    router-view

    • 匹配routes数组path,展示routes对应项的Component
    • routes配置的component叫做路由组件,可用router-view标签展示

    app.vue

    <template>
      <div id="app">
        <div class="nav">
          <router-link class="nav" to="/Island" active-class="active-nav">
            Island
          </router-link>
          <router-link class="nav" to="/Polaris" active-class="active-nav">
            Polaris
          </router-link>
        </div>
        <div class="con">
          <router-view />
        </div>
      </div>
    </template>
    
    <script>
    export default {
      name: "App",
    };
    </script>
    
    <style scoped>
    #app {
      display: flex;
       400px;
      gap: 10px;
      height: 100px;
    }
    .nav {
      flex-basis: 100px;
      display: flex;
      flex-direction: column;
      justify-content: flex-start;
    }
    .con {
      flex-grow: 1;
      background: rgb(126, 97, 143, 0.5);
    }
    .active-nav {
      background: lightseagreen;
    }
    </style>
    

    几个注意点

    routes里面配置的是路由组件,一般放在pages目录里面,而一般组件放在component目录下面
    路由切换时,被隐藏的路由组件默认会被销毁,需要的时候会再次挂载
    每个路由组件都有自己的routes信息
    整个应用只有一个$router

  • 相关阅读:
    单步调试理解webpack里通过require加载nodejs原生模块实现原理
    webpack打包过程如何调试?
    django-数据库之连接数据库
    django-模板之include标签(十五)
    django-模板之静态文件加载(十四)
    django-模板之过滤器Add(十三)
    django-模板之with标签(十二)
    django-模板之for empty(十一)
    django-模板之if语句(九)
    django-模板之自动转义autoescape(八)
  • 原文地址:https://www.cnblogs.com/ltfxy/p/15894436.html
Copyright © 2020-2023  润新知