欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

Vue中实现路由传参的多种方法探讨

最编程 2024-08-01 19:38:50
...

编程式路由传参

除了使用 <router-link> 创建 a 标签来定义导航链接,我们还可以借助 router 的实例方法,通过编写代码来实现。

  1. 通过 params 传递
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

组件获取数据

当一个路由被匹配时,它的 params 的值将在每个组件中以 this.$route.params 的形式暴露出来。

const Details = {
  template: '<div>Details {{ $route.params.id }} </div>',
  created() {
    // 监听路由变化
    this.$watch(
      () => this.$route.params,
      (toParams, previousParams) => {
        // 对路由变化做出响应...
      }
    )
  },
}

通过 query 传递

这种情况下 query (查询参数)传递的参数会显示在 url 后面,如:/details/001?kind=car。

路由配置

使用 query 时,以下三种方式都是可行的:
1.this.$router.push('/details/001?kind=car')
2.this.$router.push({ path: '/details/001', query: { kind: "car" }})
3.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

通过 hash 传递(同query)组件通过 $route.hash.slice(1) 获取

通过 props 进行传递

在组件中使用 $route 会与路由紧密耦合,这限制了组件的灵活性,因为它只能用于特定的 URL。虽然这不一定是件坏事,但我>们可以通过 props 配置来解除这种行为。

对象模式

路由配置

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。

其他方式

1. 通过 Vuex 进行传递

    1. store 存储状态;
    2. A 组件更改 store 中的状态;
    3. B 组件从 store 中获取。

2.通过前端本地存储等方式

    1. Local Storage;
    2. Session Storage;
    3. IndexedDB;
    4. Web SQL;
    5. Cookies。

以上内容仅供自己学习,查找方便