vue-动态路由

2020-11-21  本文已影响0人  望月成三人

准备工作

cnpm install axios --save

代码解析

<template>
  <div id="app">
    <div id="nav">
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link> |
      <router-link to="/me">Me</router-link> |
      <router-link to="/new">New</router-link> |
      <router-link to="/weather">Weather</router-link> |


    </div>
    <!--路由处理 -->
    <router-view/>
  </div>
</template>
import Vue from 'vue'
import VueRouter from 'vue-router'
iimport New from '../views/New.vue'
import Weather from '../views/Weather.vue'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
  ...
  {
   # location自定义的变量,可以设置多个如:/weather/:location:area
    path: "/weather/:location",
    name: "Weather",
    component: Weather
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router

<template>
    <div class="content">
        <h2>城市id: {{location}}</h2>
        <h3>城市名称:{{city}}</h3>
        <h3>省会:{{capital}}</h3>
    </div>
</template>
<script>
import axios from 'axios'
export default {
    data() {
        return {
           // 页面传值的location值,在这里被接受
            location:this.$route.params.location,
            city:null,
            capital:null
        }
    },
    async beforeMount() {
        let key = "CCCC";
        let http_url = `https://geoapi.qweather.com/v2/city/lookup?location=${this.location}&key=${key}`;
        let res = await axios.get(http_url)
        let res_data = res.data
        console.log(res)
        if (res_data.code == 200) {
            this.city = res_data.location[0].name,
            this.capital = res_data.location[0].adm1
        }
    }
}
</script>

执行效果:


image.png
上一篇 下一篇

猜你喜欢

热点阅读