【问题标题】:Vuejs Displaying a component multiple times with Axios in itVuejs多次显示带有Axios的组件
【发布时间】:2018-12-05 17:34:15
【问题描述】:

我已经尝试了一个小时,但没有运气。我有 2 个组件。第一个组件是动态的,第二个组件只是获取用户地理位置。然后地理位置会显示在第一个组件中。

我的问题是我在页面上多次显示第一个组件,每次显示它都会发出低效的 GET 请求。如果我显示该组件 3 次,它将发出 3 个 GET 请求。

重写这个最好的方法是什么?

感谢您的帮助

组件 1:

<template>
    <section id="under-info">
        THe user is from <ip_info></ip_info>
    </section>
</template>

<script>
    export default {
    }
</script>

组件 2:

<template>

    <span id="user-city">
        {{value}}
    </span>


</template>

<script>
    export default {
        mounted: function () {
            this.$nextTick(function () {
                this.getIpInfo(this.param)
            })
        },
        props:['param'],
        data: function () {
            return {
                value:null
            }
        },
        methods:{
            getIpInfo(){
                var vm = this
                delete axios.defaults.headers.common["X-Requested-With"];
                delete axios.defaults.headers.common["X-CSRF-TOKEN"];
                axios
                    .get('http://api.ipstack.com/check?access_key=?',{
                        timeout: 1000
                    })
                    .then(function(response) {
                        vm.value = response.data['city]
                    })
            }
    },
    }
</script>

【问题讨论】:

  • 是否可以从您的地理定位 api 获得多个位置?如果没有,那么您无论如何都必须为每个位置进行 api 调用
  • 我的问题是,对于同一个用户,我在同一页面上显示该组件 3 次,每次显示它时,都会调用一个我不喜欢的 GET 请求。我想调用一次 GET 方法并显示 3 次用户位置。

标签: laravel laravel-5 vue.js vuejs2 vue-component


【解决方案1】:

将代码包装在您想要在组件中重用此值 3x 的位置。

<template>
    <div>
        The user is from {{location}}, and {{location}} is a great place.  They have a baseball team in {{location}}
    </div>
</template>

<script>
    export default {
        mounted: function () {
            this.$nextTick(function () {
               if(this.needLocation){
                this.getIpInfo(this.param)
               }
            })
        },
        props:['param', 'needLocation'],
        data: function () {
            return {
                location:null
            }
        },
        methods:{
            getIpInfo(){
              this.location = //results from your API call
        }
    }
</script>

【讨论】:

  • 我的第一个组件是通过不同的博客文章插入的,但在某些情况下不是。根据您的建议,即使博客可能不需要它,我也需要每次都进行 API 调用。我所有的博客都是从数据库中动态显示的。
  • 能否传入一个反映需要进行api调用的prop?然后用那个道具包装api请求?更新上面的答案。
  • 如果你愿意,你可以用条件包装整个 $nextTick 函数
猜你喜欢
  • 2020-01-09
  • 2019-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-27
  • 2018-04-23
  • 2021-07-08
  • 2019-05-28
相关资源
最近更新 更多