vue-动态路由
2020-11-21 本文已影响0人
望月成三人
准备工作
- 新建项目,
vue create routeapp
- 选择手动设置-route-history输入yes
- yes表示使用hostory模式,url格式好看,后台需要设置相应规则
- no 表示使用的是hash值,后台不用进行任何设置,使用的是#锚点定位的方式
- 选择手动设置-route-history输入yes
- 安装请求组件
cnpm install axios --save
代码解析
- 本次代码已history模式为实例
- App.vue的导航
<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>
- index.js中声明路由组件
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
- Weather.vue组件
<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