闽公网安备 35020302035485号
const routes = [
// 动态段以冒号开始
{ path: 'details/:id', name: "details", component: Details },
]
备注:router.push() 方法的参数可以是一个字符串路径,或者一个描述地址的对象。const Home = {
template: '<div @click="toDetails">To Details</div>',
metheds: {
toDetails() {
// 字符串路径
this.$router.push('/details/001')
// 带有路径的对象
this.$router.push({path: '/details/001'})
// 命名路由,路由配置时,需要 name 字段
this.$router.push({ name: 'details', params: { id: '001' } })
}
}
}
注意,如果提供了 path,params 会被忽略:// `params` 不能与 `path` 一起使用
router.push({ path: '/details', params: { id: '001' } }) // -> /details
const Details = {
template: '<div>Details {{ $route.params.id }} </div>',
created() {
// 堆代码 duidaima.com
// 监听路由变化
this.$watch(
() => this.$route.params,
(toParams, previousParams) => {
// 对路由变化做出响应...
}
)
},
}
this.$router.push('/details/001?kind=car')
this.$router.push({ path: '/details/001', query: { kind: "car" }})
this.$router.push({ name: 'details', params: { id: '001' }, query: { kind: 'car' }})
组件获取数据const Details = {
template: '<div>Details {{ $route.query.kind }} </div>',
created() {
// 监听路由变化
this.$watch(
() => this.$route.query,
(toParams, previousParams) => {
// 对路由变化做出响应...
}
)
},
}
要对同一个组件中参数的变化做出响应的话,你可以简单地 watch $route 对象上的任意属性,在这个场景中,就是 $route.query 。this.$router.push('/details/001#car')
this.$router.push({ path: '/details/001', hash: '#car'})
this.$router.push({ name: 'details', params: { id: '001' }, hash: 'car'})
const Details = {
template: '<div>Details {{ $route.hash.slice(1) }} </div>',
}
const User = {
template: '<div>User {{ $route.params.id }}</div>'
}
const routes = [{ path: '/user/:id', component: User }]
将上面的代码替换成 props 的形式,如下:const User = {
props: ['id'], // 组件中通过 props 获取 id
template: '<div>User {{ id }}</div>'
}
// 路由配置中,增加 props 字段,并将值 设置为 true
const routes = [{ path: '/user/:id', component: User, props: true }]
注意:对于有命名视图的路由,你必须为每个命名视图定义 props 配置:const routes = [
{
path: '/user/:id',
components: { default: User, sidebar: Sidebar },
// 为 User 提供 props
props: { default: true, sidebar: false }
}
]
2. 对象模式const routes = [
{
path: '/hello',
component: Hello,
props: { name: 'World' }
}
]
组件中获取数据const Hello = {
props: {
name: {
type: String,
default: 'Vue'
}
},
template: '<div> Hello {{ name }}</div>'
}
<Hello /> 组件默认显示 Hello Vue,但路由配置了 props 对象,当路由跳转到 /hello 时,会显示传递过来的 name, 页面会显示为 Hello World。// 创建一个返回 props 的函数
const dynamicPropsFn = (route) => {
return { name: route.query.say + "!" }
}
const routes = [
{
path: '/hello',
component: Hello,
props: dynamicPropsFn
}
]
组件获取数据const Hello = {
props: {
name: {
type: String,
default: 'Vue'
}
},
template: '<div> Hello {{ name }}</div>'
}
此时页面将渲染:
3. B 组件从 store 中获取。