前端路由(v-router)

1.什么是路由

路由(英文:router)就是对应关系

2.什么是前端路由

通俗易懂的概念:Hash地址(就是之前理解的锚链接)与组件之间的对应关系

而hash地址指的就是锚链接后面的值举个例子:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .box{
      height: 800px;
    }
    #b1{
      background-color: rgb(216, 74, 74);
    }
    #b2{
      background-color: pink;
    }
    #b3{
      background-color: orange;
    }
    #b4{
      background-color: rgb(62, 83, 90);
    }
    .side-bar{
      width: 220px;
      height: 45px;
      position: fixed;
      top: 0;
      left: 50%;
    }
  </style>
</head>
<body>
  <div class="side-bar">
    <a href="#b1">b1</a>
    <a href="#b2">b2</a>
    <a href="#b3">b3</a>
    <a href="#b4">b4</a>

  </div>
  <div class="box" id="b1"></div>
  <div class="box" id="b2"></div>
  <div class="box" id="b3"></div>
  <div class="box" id="b4"></div>
</body>
</html>

注意:本地文件的地址在浏览器上运行时如果加入锚链接,则会跳转到锚链接的位置,
例如href=“#b1”就是跳转到id值为b1的区域位置,此时地址上会附加上hash地址,而路由就是hash与组件之间的以一一对应关系,而不同的hash就对应不同的组件页面。

3.前端路由的工作方式

  1. 用户点击了页面上的路由链接(a链接)
  2. 导致了URL地址栏中的Hash值发生了变化
  3. 前端路由监听了到Hash地址的变化
  4. 前端路由把当前Hash地址对应的组件渲染都浏览器中

 

path:hash地址   component:组件

4.vue-router的的基本使用

vue-router是vue.js官方给出的路由解决方案。它只能结合vue项目进行使用,I能够轻松的管理SPA项目中组件的切换。
vue-router 的官方文档地址:https://router.vuejs.org/zh/

5.vue-router安装和配置的步骤

        1.安装vue-router包  

安装命令如下:npm i vue-router@3.5.2 (版本)+ -S(表示记录到dependencies节点下)

        2.创建路由模块(在src/router/index.js)

//src/router/index.js  就是当前模块下的router模块

//1.导入Vue和VueRouter的包
import Vue from 'vue'
import VueRouter from 'vue-router'

//2.调用Vue.uer()函数,叭VueRouter安装为Vue的插件
// Vue.use()函数的作用,就是来安装插件的
Vue.use(VueRouter)

//3.创建路由的实例对象
const router = new VueRouter()

//4.向外共享路由的实例对象
export default router

        3.导入并挂载路由模块)(main.js)

import Vue from 'vue'
import App from './App.vue'
// 导入路由模块:拿到路由的实例对象
import router from './router/index.js'

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
  // 在Vue项目中,要想把路由用起来,必须把路由实例对象,通过下面的方式进行挂载
  // router:路由的实例对象
  router,
}).$mount('#app')

        4.声明路由链接和占位符

        在index.js中添加

         在所在父组件用路由占位符去占位

网页上如果要声明链接的话用Router-link不用a标签

1.路由重定向

           路由重定向指的是:用户在访问地址A的时候,强制用户跳转到地址C,从而展示特定的组件页面。通过路由规则的redirect属性,指定一个新的路由地址,可以很方便地设置路由的重定向:

只需要在router目录下添加redirect,path添加的路径为根目录

 2.嵌套路由

通过路由实现组件的嵌套展示,叫做嵌套路由

首先必须在要定义的相对父组件里面定义一个router-view来占据一个位置,而后在声明链接(哈希值)

而后通过children属性来声明子路由规则

 在src/router/index.js路由模块中,导入需要的组件,并使用children属性声明子路由规则:

声明时一定要注意哈希地址要一一对应

这里要注意的是一定要将子路由的匹配规则写在其相对应的父组件里面,如果在还需要声明重定向的话需要在其父组件里面去重定向声明一下格式如上所示

还有一点就是“默认子路由”,当不声明重定向时,在子链接的哈希地址为空,组件会默认该链接是默认的子路由链接实例如下:

 特性:一展示父组件会默认展示子路由的内容

4.动态路由匹配

动态路由指的是:把 Hash地址中可变的部分定义为参数项,从而提高路由规则的复用性。

在vue-router中使用英文的冒号(:)来定义路由的参数项。示例代码如下:

        注意:在hash地址中,/ 后面的参数项目,叫做‘路径参数

                        在路由“参数对象”中,需要使用this.$route.params 来访问路径参数

                    在hash地址中后面的参数项,叫做"查询参数"

                        在路由“参数对象”中,需要使用this.$route.query 来访问路径参数

                    在this.$route中,path只有路径部分;fullpath是完整的地址

                       

5.声明式导航&编程式导航
在浏览器中,点击链接实现导航的方式,叫做声明式导航。例如:
普通网页中点击<a>链接、vue 项目中点击<router-link>都属于声明式导航

在浏览器中,调用API方法实现导航的方式,叫做编程式导航。例如:
普通网页中调用location.href跳转到新页面的方式,属于编程式导航

        5.1vue-router中的编程式的导航API

vue-router提供了许多编程式导航的API,其中最常用的导航API分别是:

  •       this.$route.push('hash地址')

跳转到指定的hash地址,并增加一条历史记录

  •       this.$router.replace('hash地址')        

跳转到指定的hash地址,并替换掉当前的历史记录

  •       this.$router.go(数值n)

根据n的值来确定需要回退的次数的历史记录

5.5 $router.go的简化用法
在实际开发中,一般只会前进和后退一层页面。因此vue-router提供了如下两个便捷方法:

注意:如果在行内使用变成导航跳转的时候,this必须shenglue,否则会报错

  • $router.back()
  • $router.forward()

6.导航护卫

导航收尾可以控制路由的访问权限,示意图如下

6.1 全局前置守卫

每次发生路由的导航跳转时,都会触发全局前置守卫。因此,在全局前置守卫中,程序员可以对每个路由进行访问权限的控制:

// 创建路由实例对象
const router = new VueRouter({...})

// 调用路由实例对象的beforeEach方法,即可声明“全局前置守卫”
// 每次发生路由导航跳转的时候,都会自动触发fn这个"回调函数"

reouter.beforeEach(fn)

 6.2守卫方法的形参

只要发生了路由的跳转,别烦会触发beforeEach的指定的function回调

全局前置守卫的回调函数中接受3个形参,格式为:

// 创建路由实例对象
const router = new VueRouter({...})

// 全局前置守卫
router.beforeEach((to,from,next)=>{
    // to 表示将要访问的路由的信息对象
    // from 是将要离开的路由信息对象
    // next 是一个函数,调用next()表示放心,允许这次路由导航

})

// 调用路由实例对象的beforeEach方法,即可声明“全局前置守卫”
// 每次发生路由导航跳转的时候,都会自动触发fn这个"回调函数"

reouter.beforeEach(fn)

注意:next()表示放行的意思,所以如果需在回调函数里面执行next函数next()

当前用户拥有后台主页的访问权限,直接放行: next()
当前用户没有后台主页的访问权限,强制其跳转到登录页面: next('/login')

当前用户没有后台主页的访问权限,不允许跳转到后台主页:next(false)

分析:

  1. 要拿到用户将要访问的hash的地址
  2. 判断hash地址是否等于/main。
  • 如果等于/main,证明需要登录之后才能访问成功
  • 如果不等于/main,则不需要登录,直接放行,next()

      3.如果访问的地址是/main,则需要读取localStorage中的token值

  • 如果有token,则放行
  • 如果没有token,则强制跳转到/login登录页
router.beforeEach(to,from,next)=>{
    if(to.path == '/main'){
        const token = localSorage.getItem('token')
        if(){
            next() // 访问的后台主页,且有token的值
        }else{
            next('/login')  // 访问的是后台主页,但是没有token的值
        }
    }else{
        next()   // 访问的不是后台主页,直接放行
    }

})

   

 

  • 4
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的天气预报查询网站的Vue代码示例,包括查询主页、城市切换、七天天气展示、天气详情页面。 首先,我们需要在`App.vue`中定义路由和导航栏: ```html <template> <div id="app"> <nav> <router-link to="/">查询</router-link> </nav> <router-view /> </div> </template> <script> export default { name: "App", components: {}, }; </script> <style> nav { display: flex; justify-content: center; background-color: #2196f3; padding: 10px; } nav a { color: #fff; margin: 0 10px; text-decoration: none; } nav a.active { font-weight: bold; } </style> ``` 然后,在`main.js`中创建路由和Axios实例: ```javascript import Vue from "vue"; import App from "./App.vue"; import VueRouter from "vue-router"; import axios from "axios"; Vue.use(VueRouter); Vue.prototype.$http = axios; const routes = [ { path: "/", component: Home, }, { path: "/weather/:city", component: Weather, }, ]; const router = new VueRouter({ mode: "history", routes, }); new Vue({ router, render: (h) => h(App), }).$mount("#app"); ``` 其中,`Home`和`Weather`是两个组件,分别对应查询主页和天气详情页面。`Vue.prototype.$http = axios`语句将Axios实例添加到Vue的原型中,以便在组件中使用。 接下来,我们可以实现查询主页组件`Home.vue`: ```html <template> <div> <h1>天气预报查询</h1> <form @submit.prevent="search"> <label for="city">城市:</label> <select v-model="city"> <option value="北京">北京</option> <option value="上海">上海</option> <option value="广州">广州</option> <option value="深圳">深圳</option> <option value="成都">成都</option> </select> <button type="submit">查询</button> </form> </div> </template> <script> export default { name: "Home", data() { return { city: "北京", }; }, methods: { search() { this.$router.push(`/weather/${this.city}`); }, }, }; </script> ``` 这里我们使用了一个表单来获取用户输入的城市名称,并在提交表单时将城市名称作为参数传递给`Weather`组件。 然后,我们可以实现天气详情页面组件`Weather.vue`: ```html <template> <div> <h1>{{ city }}天气预报</h1> <div> <h2>今天</h2> <img :src="weather.today.icon" :alt="weather.today.text" /> <p>温度:{{ weather.today.temp }}℃</p> <p>湿度:{{ weather.today.humidity }}</p> <p>风向:{{ weather.today.wind }}</p> </div> <div v-for="(day, index) in weather.forecast" :key="index"> <h2>{{ day.date }}</h2> <img :src="day.icon" :alt="day.text" /> <p>温度:{{ day.high }}℃ ~ {{ day.low }}℃</p> <p>风向:{{ day.wind }}</p> </div> </div> </template> <script> export default { name: "Weather", data() { return { city: "", weather: null, }; }, mounted() { this.city = this.$route.params.city; this.getWeather(); }, watch: { "$route.params.city": function () { this.city = this.$route.params.city; this.getWeather(); }, }, methods: { async getWeather() { const response = await this.$http.get( `https://api.openweathermap.org/data/2.5/weather?q=${this.city}&appid=YOUR_API_KEY&units=metric&lang=zh_cn` ); const data = response.data; this.weather = { today: { temp: data.main.temp, humidity: data.main.humidity, wind: data.wind.speed, icon: `https://openweathermap.org/img/w/${data.weather[0].icon}.png`, text: data.weather[0].description, }, forecast: [], }; const forecastResponse = await this.$http.get( `https://api.openweathermap.org/data/2.5/forecast?q=${this.city}&appid=YOUR_API_KEY&units=metric&lang=zh_cn` ); const forecastData = forecastResponse.data; for (let i = 0; i < forecastData.list.length; i += 8) { const item = forecastData.list[i]; this.weather.forecast.push({ date: item.dt_txt.slice(0, 10), high: item.main.temp_max, low: item.main.temp_min, icon: `https://openweathermap.org/img/w/${item.weather[0].icon}.png`, text: item.weather[0].description, wind: item.wind.speed, }); } }, }, }; </script> ``` 在这里,我们使用了`mounted`钩子和`watch`属性来获取路由参数(城市名称)并获取天气数据。我们使用了`openweathermap`API来获取天气数据,并将其存储在`weather`对象中,然后在模板中使用`v-for`指令来循环渲染未来七天的天气信息。 最后,在`main.js`中,我们需要在Axios实例中添加API密钥: ```javascript import Vue from "vue"; import App from "./App.vue"; import VueRouter from "vue-router"; import axios from "axios"; Vue.use(VueRouter); Vue.prototype.$http = axios.create({ baseURL: "https://api.openweathermap.org/data/2.5", params: { appid: "YOUR_API_KEY", units: "metric", lang: "zh_cn", }, }); const routes = [ { path: "/", component: Home, }, { path: "/weather/:city", component: Weather, }, ]; const router = new VueRouter({ mode: "history", routes, }); new Vue({ router, render: (h) => h(App), }).$mount("#app"); ``` 在这里,我们使用了`axios.create`方法来创建一个新的Axios实例,并在其参数中添加了`baseURL`和`params`,以便在每个请求中自动添加API密钥和其他参数。 这是一个简单的天气预报查询网站的Vue代码示例,你可以根据实际需求进行修改和完善。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值