【问题标题】:I have a route component, why are my props not automatically updating when I set them in the route definition?我有一个路由组件,为什么我在路由定义中设置道具时不会自动更新?
【发布时间】:2020-04-29 14:47:28
【问题描述】:

我的索引书列出了所有已注册的书籍,当我单击编辑特定书籍时,它确实在路线中获得了特定书籍的 id,但我的 props 元素没有得到它,这是什么错误! 我该如何解决?

下面是我的索引页上的代码:

<router-link :to="{ name: 'update_book', params: {id: book.id} }"> <font-awesome-icon icon="pen-square" /> </router-link>

在我的更新页面中:

<script>
 props: ['id'],
 data() {
  return {
   books: [],
  };
 },
 methods: {
  getBook(id) {
   axios.get(`http://localhost:3000/api/v1/books/${id}`) // Gets an specif book
    .then((response) => { this.books = response.data; });
 },
 created() {
  this.getBook(this.id);
 },
 watch: {
  $route() {
   this.getBook(this.id);
 },

【问题讨论】:

  • 你能显示你定义路线的代码吗?我的理解是,只有当它是“路由组件”时才会自动设置参数。请参阅示例here
  • { 路径:'/update_book/:id',名称:'update_book',组件:UpdateBook,道具:真,},
  • 为什么要在那儿? params 不会向 props 传递任何东西
  • 什么意思?

标签: vue.js vue-router vue-props


【解决方案1】:

路由器不要将id传递给props。在您的情况下,您可以在this.$route.params中找到id

即使您在路由器本身中使用/book/:id 之类的东西,id 参数也将存在于this.$route.params.id 中。

所以你需要类似的东西:

 created() {
  this.getBook(this.$router.params.id);
 },

顺便说一句,在观察者中也是如此。

【讨论】:

  • 我收到此错误“TypeError: this.$router.params is undefined”
  • 我的错。this.$route不是routeR
  • 没问题,兄弟,最好将问题更改为“如何从 vue-router 中的路由获取参数”?
  • 是的,我认为这可行。我认为最初的问题可以更好地表述为“我有一个route component,为什么当我在路由定义中设置它们时我的道具没有自动更新?”答案还有待观察。
  • 同意城里的先生。我可以编辑它以获得一些便宜的业力吗?)
猜你喜欢
  • 2018-11-04
  • 2018-10-31
  • 1970-01-01
  • 2021-12-05
  • 2020-08-19
  • 2020-01-11
  • 1970-01-01
  • 2013-11-26
  • 1970-01-01
相关资源
最近更新 更多