【问题标题】:Why is this.$route.params null?为什么 this.$route.params 为空?
【发布时间】:2022-10-25 13:34:08
【问题描述】:

我想将数据传递到另一个页面,我使用以下代码:

  this.$router.push({ path: '/guard/foreigner-list', params: data});

然后我希望项目等于数据,但项目为空

let item = this.$route.params;

【问题讨论】:

    标签: vue.js vue-router


    【解决方案1】:

    您没有发布与更改路线过程相关的整个代码。但根据Vue Router documentation

    如果提供了path,则params 将被忽略,而查询不是这种情况,如示例中所示。相反,您需要提供路由的name 或使用任何参数手动指定整个path

    因此,如果您在 router.js 文件中定义了一个名为 user 的路由,如下所示:

    import User from "../views/User"
    
    const routes = [
      { 
        path: '/user/:id',
        name: 'User',
        component: User
      }
    ]

    然后您可以使用以下代码将navigate programmaticallyHome.vue 转换为User.vue

    Home.vue:

    <template>
      <div class="home">
        <button @click="navigFunc">click to navigate</button>
      </div>
    </template>
    
    <script>
    
    export default {
      name: 'Home',
      methods: {
        navigFunc: function () {
          const id = '123';
          // using "name" not "path"
          this.$router.push({ name: 'User', params: { id } });
        }
      }
    }
    </script>

    User.vue:

    <template>
    <section>
      <h1>User page</h1>
    </section>
    </template>
    
    <script>
    export default {
      name: "User",
      mounted() {
      /* access the params like this */
        console.log(this.$route.params)
      }
    }
    </script>
    
    <style scoped>
    
    </style>

    请注意,我定义的变量 (id) 与 router.js 中定义的 params 相同(路径:'/user/:id')。

    【讨论】:

      【解决方案2】:

      vue-router@4.1.4 (2022-08-22) 开始通过params 传递对象不再是可行的选择,因为它被视为反模式。

      然而,

      这种反模式有多种替代方案:

      • 将数据放在像 pinia 这样的存储中:如果数据在多个页面中使用,这很重要

      • 通过在路由的路径上定义数据或将其作为查询参数传递来将数据移动到实际参数:如果您有小块数据可以放入 URL 并且在重新加载页面时应该保留,这很重要

      • 将数据作为状态传递以将其保存到历史 API 状态:...

      • 在导航守卫期间将其作为新属性传递给 to.meta:...

      【讨论】:

        猜你喜欢
        • 2018-11-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-10
        • 2016-04-06
        • 2016-04-06
        • 2020-04-07
        • 1970-01-01
        相关资源
        最近更新 更多