在Vue中推送到一个路由时,我们可以通过props传递数据吗?

huangapple go评论58阅读模式
英文:

Can we pass data via props when pushing to a route in Vue?

问题

我问这个问题是为了了解当导航到新路由时是否可以通过 props 传递一些数据。因为我读了一些推荐将数据作为 props 传递的文章,我想了解这是否真的有效。

根据我查阅的文档,在路由中传递 props 仅在两种情况下有效:

  1. 当您希望将传递的参数用作 props 时。
{ path: '/user/:id', component: User, props: true },
  1. 当您希望传递一些静态数据时。
{ path: '/user/:id', component: User, props: { value: 123 } },

在这两种情况下,我们在路由定义中使用 props 属性。

我的问题是,如果我们想在推到新路由时通过 props 传递一些数据,是否可行?因为我尝试过这个,发现传递的 props 总是 undefined。GitHub 上有相同的问题,但我不理解他们的最后一条评论。

以下是演示,显示模板中传递的 props 总是 undefined。

const Comp1 = Vue.component('Comp1', {
  template: `
    <div>Comp1- <button @click="$router.push({name: 'Comp2',props: { value: 1234 })">Push to route with props</button>
    </div>`,
});

const Comp2 = Vue.component('Comp1', {
  template: `<div>Comp2 - {{ value }} <button @click="$router.push({name: 'Comp1' })">Go back</button> </div>`,
  mounted() { console.log('Prop value- ', this.value) },
  props: ['value']
});

const router = new VueRouter({
  routes: [{
      path: '/',
      name: "Comp1",
      component: Comp1,
    },
    {
      path: '/comp1',
      name: "Comp2",
      component: Comp2,
    }
  ]
});

const app = new Vue({
  el: "#app",
  router,
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/vue-router@3.6.5/dist/vue-router.js"></script>
<div id="app">
  <router-view></router-view>
</div>
英文:

I am asking this question to understand whether we can pass some data via props when navigating the new route. Because I read a few articles which recommend passing data as props and I want to understand if this really works.

As much as I looked into the documentation, passing props in routes works with only two cases-

  1. When you want to use passed params as props.
{ path: &#39;/user/:id&#39;, component: User, props: true },
  1. When you want to pass some static data.
{ path: &#39;/user/:id&#39;, component: User, props: { value: 123 } },

In both cases, we use the props property in the route's definition.

My question is if we want to pass some data via props when we push to a new route, is it doable? Because I tried this and noticed that passed props are always undefined. There is the same issue on GitHub that stated the problem but I didn't understand their last comment.

Here is the demo which shows that passed props are always undefined in the template.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const Comp1 = Vue.component(&#39;Comp1&#39;, {
  template: `
  &lt;div&gt;Comp1- &lt;button @click=&quot;$router.push({name: &#39;Comp2&#39;,props: { value: 1234 },
	  })&quot;&gt;Push to route with props&lt;/button&gt;
  &lt;/div&gt;`,
});

const Comp2 = Vue.component(&#39;Comp1&#39;, {
  template: `&lt;div&gt;Comp2 - {{ value }} &lt;button @click=&quot;$router.push({name: &#39;Comp1&#39;
	  })&quot;&gt;Go back&lt;/button&gt; &lt;/div&gt;`,
  mounted() { console.log(&#39;Prop value- &#39;, this.value) },
  props: [&#39;value&#39;]
});

const router = new VueRouter({
  routes: [{
      path: &#39;/&#39;,
      name: &quot;Comp1&quot;,
      component: Comp1,
    },
    {
      path: &#39;/comp1&#39;,
      name: &quot;Comp2&quot;,
      component: Comp2,
    }
  ]
});

const app = new Vue({
  el: &quot;#app&quot;,
  router,
})

<!-- language: lang-html -->

&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;https://unpkg.com/vue-router@3.6.5/dist/vue-router.js&quot;&gt;&lt;/script&gt;
&lt;div id=&quot;app&quot;&gt;
  &lt;router-view&gt;&lt;/router-view&gt;
&lt;/div&gt;

<!-- end snippet -->

答案1

得分: 2

以下是翻译好的部分:

"所说的是,除非它在路由记录的参数中或静态提供的情况下,否则无法动态传递数据到路由。"

"路由参数是URL的一部分,应该与某些内容匹配,但仍与给定的组件相关联。例如,在此路由记录中,:id 就是一个路由参数。它是一个将是动态的内容。"

"现在,路由记录中的 props 属性用于以不同方式读取URL中的参数。您可以通过两种方式实现这一点:"

"那么,为什么要使用props呢?"

"我可能错了,但我看到的唯一用例是当您想将一个组件用作路由的视图时。"

"就我的经验来看,这是很少发生的事情。路由URL中的参数通常与资源的ID匹配,通常在将其传递给组件之前进行获取。因此,我会无论如何使用一个包装器,永远不会在路由记录上使用props。"

"答案是:"

"当推送到新路由时,您无法传递props。如果在路由记录中使用 props: true,则props将从URL中读取,否则将从路由定义(记录)中静态定义。"

"如果要推送数据:"

  • "要么您在URL中提供资源ID,以便要推送到的页面获取它。"
  • "要么您将其保存在 localStorage 中(不建议,这意味着您的应用架构可能不适合您的需求),然后在下一页检索它。"
英文:

What is said is that you can't dynamically pass data to a route unless it's in the parameters of the route record or statically provided

What is a route parameter ?

A route parameter is a part of the url that should match something, but that is still tied to a given a component. For example, in this route record, :id is a route parameter. It's something that will be dynamic.

const routes: Route[] = [
  {
    name: &#39;user-detail&#39;,
    path &#39;/users/:id&#39;,
    component: UserDetailView,
  },
];

Now, the props property in the route record is something used to read differently the parameter in the URL. You can achieve this in 2 ways:

export default defineComponent({
  props: {
    id: string; // Route params are strings, I&#39;m not sure if you can parse them first
  },

  // Composition API
  setup(props) {
    // Method 1
    const route = useRoute();
    const userId = route.params.id;

    // Method 2
    const userIdFromProps = props.id
  },

  // Options API
  created() {
    // Method 1
    const userId = this.$route.params.id;

    // Method 2
    const userIdFromProps = this.id; (this.id reads the prop id)
  },
});

What's the point of using props then ?

I may be wrong, but the only use case I see is when you want to use a component as a route's view.

You have a component that accepts props that you use in another view. And this component matches exactly your requirements, so instead of wrapping it in a view, you directly use it as a route's view, and props are automatically passed down.

My thoughts

Given my experience in many apps built with vue, this is something that rarely happens. Params in the route url usually match a ressource's ID, and you usually fetch it before passing it down to a component. So I'd use a wrapper anyway and would never use props on route records.

The answer:

After all those explanations I forgot to answer, because the question shouldn't have to be asked:

You can't pass props when pushing to a new route. The props will be read either from the URL if you use props: true in your route record, or from the route definition (record) if you statically defined it.

If you want to push data:

  • Either you provide the resource id in the URL to let the page you're pushing to fetching it
  • Either you save it in the localStorage (not recommended, that means your app architecture is maybe not adapted to your needs), and retrieve it on your next page

huangapple
  • 本文由 发表于 2023年2月23日 19:19:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75544115.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定