1: 传递参数主要有两种方式: params, query
params 的类型格式:
配置路由格式: '/router/:id'
传递方式: 在path 后边跟上对应的值
传递后形成的路径: /router/123, /router/abc
query 的类型:
2: 配置路由格式: /router, 也就是普通配置
传递的方式就是一个对象, 使用query 的key 作为传递参数的方式。
最开始现实就是App.vue 文件, App.vue 文件是入口文件。 导入App.vue文件然后挂载到vue 的实例上去。
在App.vue 跟组件上定义一个连接,
<router-link :to"'/user/+userId'"></router-link>
然后在User 组件中就可以使用: this.$route.params.userid // 获取到当前的userid 值
vue-router: 传递参数的另外一种方式。
<vue-router :to="{path: '/profile', query: {name:'abc', age: 18}}">文件</vue-router>
然后在 profile 文件中使用: $route.query 就可以到数据。
3:使用按钮的方式:
点击按钮:
methods: {
userClick() {
this.$router.push('/user/' + this.userId)
},
profileClick() {
this.$router.push({
path: '/profile',
query: {
name: 'aaa',
age: 18,
height: 1.88
}
})
}
}
params 和query 传递数据:
如果传递数据比较多的时候, 可以使用query 的方式进行传递。 query 的方式可以传递一个对象。
$router 和 $route 的区别:
1: 在任何一个组件中都可以使用 this.$router
在每一个组件中console.log(this.$router);
和在main.js 中console.log(router); 打印出来的对象是一致的。
2: 在vueRouter 路由源码中, 安装插件就是相当于使用了插件的install 方法。
所有的组件都继承自vue 类的原型。 (所有的组件都会继承Vue 类的原型);
在Vue 原型上挂载一个方法, 所有的组件都可以使用。
3; object.defineProperty(obj, 'age', 18);
给给对象添加属性。
Vue-mixin({
beforeCreate() {
if(isDef(this.$option.router)) {
this._routerRoot._router = this
this._router = this.$options.router
this._router.init(this)
Vue.util.defineReactive(this, '_route', this._router.history.current)
}else {
this._routerRoot = (this.$parent && this.$aprent._routerRoot) || this
}
registerInstance(this, this)
},
destoryed() {
registerInstance(this)
}
})
Object.defineProperty(Vue.prototype, '$router', {
get () { return this._routerRoot._router }
})
Object.defineProperty(Vue.prototype, '$router', {
get () { return this._routerRoot._route }
})
// 注册为全局组件
<route-link><route-link>
<route-view><route-view>
Vue.component('RouterView', View);
Vue.component('RouterLink', Link');