路由组件传参

之前我们在组件中使用 $route 会使之与其对应路由形成高度耦合,从而使组件只能在某些特定的url上使用,限制了其灵活性。

const User= {
    template: '<div>User {{ $route.params.id }}</div>'
}
const router = new VueRouter({
    routes: [
        { path: '/user/:id', component: User }
    ]
})

使用props将组件和路由解耦:

const User = {
    props: ['id'],
    template: '<div>User {{ id }}</div>'
}

const router = new VueRouter({
    routes: [
        { path: '/user/:id, component: User, props: true }

        //  对于包含命名视图的路由,你必须分别为每个命名视图添加porps选项:
        {
            path: '/user/:id',
            component: {default: User, sidebar: Sidebar },
            props: { default: true, sidebar: false }
        }
    ]
})

这样便可以在任何地方使用该组件,使得该组件更易于重用和测试。


布尔模式

如果props被设置为true,route.params将会被设置为组件属性。


函数模式

创建一个函数返回porps,这样便可以将参数转换成另一种类型,将静态值与基于路由的值结合等等。

const router = new VueRouter({
    routes: [
        { path: '/search', component:SearchUser,props:(route)=>({ query:route.query.q }) }
    ]
})

Url: /search?q=vue会将 { query: “vue” }作为属性传递给SearchUser组件。

尽可能保持props函数为无状态的,因为它只会在路由发生变化时起作用。如果需要状态来定义props,请使用包装组件,这样vue才能对状态变化做出反应。


import Vue from 'vue'
import VueRouter from 'vue-router'
import Hello from './Hello.vue'

Vue.use(VueRouter)

function dynamicPropsFn (route) {
  const now = new Date()
  return {
    name: (now.getFullYear() + parseInt(route.params.years)) + '!'
  }
}

const router = new VueRouter({
  mode: 'history',
  base: __dirname,
  routes: [
    { path: '/', component: Hello }, // No props, no nothing
    { path: '/hello/:name', component: Hello, props: true }, // Pass route.params to props
    { path: '/static', component: Hello, props: { name: 'world' }}, // static values
    { path: '/dynamic/:years', component: Hello, props: dynamicPropsFn }, // custom logic for mapping between route and props
    { path: '/attrs', component: Hello, props: { name: 'attrs' }}
  ]
})

new Vue({
  router,
  template: `
    <div id="app">
      <h1>Route props</h1>
      <ul>
        <li><router-link to="/">/</router-link></li>
        <li><router-link to="/hello/you">/hello/you</router-link></li>
        <li><router-link to="/static">/static</router-link></li>
        <li><router-link to="/dynamic/1">/dynamic/1</router-link></li>
        <li><router-link to="/attrs">/attrs</router-link></li>
      </ul>
      <router-view class="view" foo="123"></router-view>
    </div>
  `
}).$mount('#app')

HTML5 History模式

vue-router默认hash模式–使用URL的hash来模拟一个完整的URL,于是当URL改变时,页面不会重新加载。

如果不想要很丑的hash,我们可以用路由的history模式,这种模式充分利用history.pushState API来完成URL跳转而无需重新加载页面。

const router = new VueRouter({
    mode: 'history',
    routes: [...]
})

当使用history模式时,URL就像正常的url, 例如http:/yoursite.com/user/id.

不过这种模式需要后台配置支持,因为应用是个单页客户端应用,如果后台没有正确配置,当用户在浏览器直接访问http://oursite.com/user/id就会返回404

所以呢,在服务器端增加一个覆盖所有情况的候选资源:如果URL匹配不到任何静态资源,则应该返回一个index.html页面,这个页面就是app依赖的页面。

Logo

前往低代码交流专区

更多推荐