【问题标题】:Best solution for getting {id} from url?从 url 获取 {id} 的最佳解决方案?
【发布时间】:2020-09-01 17:32:07
【问题描述】:

我正在尝试创建一个功能,个人可以创建列表,其他用户可以提交申请。 ATM 我不太明白如何从以下网址获取 ID:

'http://localhost:3000/listings/2/'

我有预感这需要 Vue 路由器和 $route.params.id?基本上我想在我的表单中列出用户申请的列表的 ID。在这种情况下,它将是 '2'

我的文件夹结构是.../listings/_id/index.vue

这是我在 DRF 中的 user_applications 模型的后端:

 listing = models.ForeignKey(Listings,  on_delete=models.CASCADE, default="1")

这是前端:我希望我可以在脚本中使用 props 值,但它似乎只能在模板中使用,哦,好吧。

  data: () => ({
    form: {
      role: null,
      company: null,
      status: "Pending"
      // listing: listings.id
    }
  }),

  props: ["listings"],
  computed: {
    ...mapGetters(["loggedInUser"])
  },

  methods: {
    submit() {
      this.$axios
        .post("/api/v1/apps/", this.form)
        .then(response => {
          console.log(response);
        })
        .catch(error => {
          console.log(error);
        });
    }
  }

【问题讨论】:

    标签: vue.js django-models nuxt.js


    【解决方案1】:

    是的,就像this.$route.params.id 一样简单。您可以直接在模板中调用$route.params.id,而无需使用this不要在你的组件中使用箭头函数!它们会去除this 的值!此外,this 上也提供所有道具和数据属性。所以this.listingthis.$route 可用,不仅在您的模板中,而且在您的Vue 组件的方法和计算属性中。

    请尝试以下方法:

      data() {
        return {
          form: {
            role: null,
            company: null,
            status: "Pending",
            listing: this.listings.id
          }
        }
      },
    

    【讨论】:

    • 太棒了!感谢您指出箭头函数的概念,我刚刚阅读了更多相关内容,它消除了我过去的一些困惑。所以本质上,this.$route.params.id 作为到期的一部分起作用,而 this.listings.id 对我的道具起作用,对吗?你也忘了扭曲形式:{} inside of return{}
    【解决方案2】:

    当您考虑使用VueRouter 时,您是在正确的轨道上。假设您的组件名称是Listing

    import VueRouter from 'vue-router';
    import Listing form './path/to/ListingComponent.vue';
    
    const router = new VueRouter({
      routes: [
        {
          path: '/listing/:id',
          component: Listing,
          // return parms.id as listingId for the `Listing` component.
          props: route => ({ listingId: route.params.id })
        }
      ]
    })
    

    通过这种方式,您将listingId 传递给propsListing

    【讨论】:

      猜你喜欢
      • 2015-07-16
      • 1970-01-01
      • 1970-01-01
      • 2020-04-12
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 2014-09-18
      • 1970-01-01
      相关资源
      最近更新 更多