对于熟悉restful风格的人来说,通过URL传值主要的方式有?传值以及/传值两种。而在vue-router中正是分别通过query和params来实现的。
路由的定义
var routes = [
{
path: '/',
component: HomePage
},
{
path: '/table',
name: 'table',
component: Table
},
{
path: '/carousel/:id/:name',
name: 'carousel',
component: Carousel
},
{
path: '/transfer',
name: 'transfer',
component: Transfer
},
{
path: '/test',
name: 'test',
component: Test
},
{
path: '/clock',
name: 'clock',
component: Clock
}
];
路由的注入
import Vue from 'vue'
import App from './App.vue'
import store from './store';
import router from './router'
import Element from 'element-ui'
import locale from 'element-ui/lib/locale/lang/en' // 默认语言包是中文
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(Element, { locale })
Vue.config.productionTip = false
/**
* 创建和挂载根实例。
* 记得要通过 router 配置参数注入路由,
* 从而让整个应用都有路由功能
*/
new Vue({
el: '#app',
store,
router,
components: { App },
template: ' '
})
URL格式
query:"/table?id=1&name=hhj"
params:"/carousel/1/hhj"
如何获取URL上的参数
query:{id:this.$route.query.id, name: this.$route.query.id}
params:{id:this.$route.params.id, name: this.$route.params.id}
如何传参
// query传参
this.$router.push({
path: '/transfer',
query: {id:1, name:'hhj'} // 定义要传入的参数
});
// params传参
this.$router.push({
name: 'clock',
params: {id:1, name:'hhj'} // 定义要传入的参数
});
GitHub源码地址
PS:在测试name和query配套使用时,发现如果path、name+query的形式书写,并且path和name指定的路由对象不同的。结果总是跳转到了name指定的那个路由上去,不知道这个是什么原因,如果有知道还请指教一下,十分感谢!