原文:
https://www.cnblogs.com/robinunix/p/11045870.html
https://www.cnblogs.com/miluluyo/p/11190648.html
一、核心代码
1、获取参数
this.$route.query.id
this.$route.query
2、页面跳转
<router-link to="/login?id=123">登录</router-link>
3、方法跳转
this.$router.push({ path: '/login', query: { id: '456' } });
二、全部代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<!--<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>-->
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>
<body>
<div id="components-demo">
<component-a></component-a>
<router-link to="/login?id=123">登录</router-link>
<router-link to="/register">注册</router-link>
<button v-on:click="fn1">测试点击调整页面</button>
<router-view></router-view>
</div>
<script type="text/javascript">
// 组件的局部注册
var ComponentA = {
data: function () {// 组件的数据
return {
count: 0
}
},
template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'// 组件的模板
};
var Component_login = {
template: '<h2>登录----{{$route.query.id}}------{{id}}-----{{name}}</h2>',
data: function () {
return {
name: 'name1',
//id: this.$route.query.id// 获取url参数,这个不可以用,不是实时的!!!
};
},
computed: {
id: function () {
return this.$route.query.id// 计算属性的 获取url参数,这个可以用
}
},
created() {
console.log(this.$route.query)
},
};
var Component_register = { template: '<h1>Component2</h1>' };
// 路由
var routerObj = new VueRouter({
routes: [
{ name:'login', path: '/login', component: Component_login },
{ name:'register', path: '/register', component: Component_register }
]
})
new Vue({
el: '#components-demo',
components: {
'component-a': ComponentA,
'component-1': Component_login,
'component-2': Component_register
},
router: routerObj,
methods: {
fn1: function () {// 跳转页面
//this.$router.push({ name: 'login', query: { id: '456' } });
this.$router.push({ path: '/login', query: { id: '456' } });
}
}
})
</script>
</body>
</html>