【问题标题】:How to use Nuxt Context to call Axios request with param如何使用 Nuxt Context 调用带参数的 Axios 请求
【发布时间】:2020-08-24 12:49:41
【问题描述】:

所以我试图让我的 Axios 使用一个参数来执行获取请求,该参数将在中结束 url

'/?user= {id}'

id 是由我的 Vuex 中的 loggedInUser.id 传入的。我知道异步函数在调用中不会接受“this”,所以我将 store 作为参数包含在内。我认为我如何传递数据的方式仍然存在问题。非常感谢任何帮助,谢谢!

  

    import { mapGetters } from "vuex";
       
       export default {
         computed: {
           ...mapGetters(["loggedInUser"])
         },
         head() {
           return {
             title: "Actors list"
           };
         },
         components: {
           EditProfile
         },
         async asyncData({ store }) {
           try {
             const body = { data: store.getters.loggedInUser.id };
             const { actors } = await $axios.$get(`/api/v1/actors/`, {
               params: {
                 user: body
               }
             });
       
             return { actors };
           } catch (e) {
             return { actors: [] };
           }
         },
         data() {
           return {
             actors: []
           };

编辑

当我从 'const body' 中删除数据并删除了 'actor' 周围的括号时,我得到了它的工作

    try {
      const body = store.getters.loggedInUser.id;
      const actors = await $axios.$get(`/api/v1/actors/`, {
        params: {
          user: body
        }
      });

【问题讨论】:

    标签: vue.js vuejs2 vuex nuxt.js


    【解决方案1】:

    您可以从Context 访问您的params

    Context 可用于特殊的 nuxt 生命周期区域,例如 asyncDatafetchpluginsmiddlewarenuxtServerInit

    【讨论】:

      【解决方案2】:

      在 Nuxt 中,使用 asyncData 钩子可以从路由上下文键中获取查询参数。

      请阅读 Nuxt.js 上下文文档。 The context provides additional objects/params from Nuxt to Vue components

      使用您的域/?user=wonderman

      asyncData({ route: { query: queryParams} }) {},
      

      变量 queryParams 是一个对象:

      { user: "wonderman" }
      

      【讨论】:

      • 嗯,我认为这不是我想要的。使用 route: 是否意味着使用 Vue 路由器进行重定向?我希望将查询参数传递给 $Axios.get 以便在页面上显示内容。
      猜你喜欢
      • 2020-07-18
      • 2019-02-28
      • 2018-04-07
      • 2020-02-19
      • 2021-02-26
      • 2020-02-05
      • 2019-01-09
      • 2019-06-08
      • 2023-03-20
      相关资源
      最近更新 更多