【问题标题】:How to get response ajax on the vue.js 2?如何在 vue.js 2 上获得响应 ajax?
【发布时间】:2017-06-12 10:11:06
【问题描述】:

我的代码是这样的:

<template>
    <a href="javascript:" class="btn btn-block btn-success" @click="addFavoriteStore($event)">
        <span class="fa fa-heart"></span>&nbsp;Favorite
    </a>
</template>

<script>
    export default{
        props:['idStore'],
        mounted(){
            this.checkFavoriteStore()
        }, 
        methods:{
            addFavoriteStore(event){
                alert('tost');
                event.target.disabled = true
                const payload= {id_store: this.idStore}
                this.$store.dispatch('addFavoriteStore', payload)
                setTimeout(function () {
                    location.reload(true)
                }, 1500);
            },
            checkFavoriteStore(){
                const payload= {id_store: this.idStore}
                this.$store.dispatch('checkFavoriteStore', payload)
                setTimeout(function () {
                   location.reload(true)
                }, 1500); 
                //get response here  
            }
        }
    }
</script>

脚本执行时会先调用checkFavoriteStore方法

通过checkFavoriteStore方法调用vuex store的action

结果会返回响应

如何获得响应?

更新

我对 vuex 商店的操作是这样的:

import { set } from 'vue'
import favorite from '../../api/favorite'
import * as types from '../mutation-types'

// actions
const actions = {
    checkFavoriteStore ({ dispatch,commit,state },payload)
    {
        favorite.checkFavorite(payload,
            data => {
                commit(types.CHECK_FAVORITE_SUCCESS)
            },
            errors => {
                commit(types.CHECK_FAVORITE_FAILURE)
                console.log(errors)
            }
        )
    }
}

// mutations
const mutations = {
    [types.CHECK_FAVORITE_SUCCESS] (state){
        state.addStatus = 'success'
    },
    [types.CHECK_FAVORITE_FAILURE] (state){
        state.addStatus = 'failure'
    }
}

export default {
    actions,
    mutations
}

还有这样的 api:

import Vue from 'vue'
import Resource from 'vue-resource'

Vue.use(Resource)

export default {

    // api check favorite exist or not
    checkFavorite (favorite, cb, ecb = null ) {
        Vue.http.post(window.Laravel.baseUrl+'/member/store/favorite/check-favorite', favorite)
            .then(
            (resp) => cb(resp.data),
            (resp) => ecb(resp.data)
        );
    }
}

【问题讨论】:

  • 能否请您向我们展示您与 AJAX 相关的代码?
  • @Belmin Bedak,这:this.$store.dispatch('checkFavoriteStore', payload)。它将在 vuex 存储上调用操作
  • 他要求的是商店中的代码,该代码调用并返回此调用的响应 this.$store.dispatch('checkFavoriteStore', payload)
  • 正如 laracast 上提到的,我认为它会在 1.5 秒后刷新页面,因此会错过任何响应????

标签: javascript ajax vue.js laravel-5.3 vuejs2


【解决方案1】:

如果您返回结果,则将调用分配给一个变量,所以 tyr:

  var res = this.$store.dispatch('checkFavoriteStore', payload);

然后您可以通过 var res 访问响应。我相信这些事件会把它还给你

更多查询:

只是一个小问题。

如果您获取商店 ID 并将其作为道具传递给组件。所以当然你也可以传递另一个道具来告诉商店是否已经被喜欢了?因此,通过对视图的 db 调用获取这些数据,从而节省了在加载后进行检查的操作,如下所示:

  <favorite-button :storeid="23" :favorited="true"></favorite-button>

所以使用喜爱的属性来相应地更改按钮?所以需要checkFavoriteStore 调用并节省额外的http请求等时间

不知道您的代码或它在做什么等,只是一个想法??

添加信息后编辑

好的,你能不能把你的http请求改成这样:

Vue.$http.post(window.Laravel.baseUrl+'/member/store/favorite/check-favorite', favorite)
  .then((response) => {
      console.log('success')
      console.log(response.data);
    return response.data;
  }, (response) => {
       console.log('success');
        console.log(response);
    return response;
  });

我已经添加了 console.logs,所以我们可以看到发生了什么。让我们看看这是否有帮助?

也可以尝试在前面加一个return,因为它需要返回到它原来的调用者

 return favorite.checkFavorite(payload,
        data => {
            commit(types.CHECK_FAVORITE_SUCCESS)
        },
        errors => {
            commit(types.CHECK_FAVORITE_FAILURE)
            console.log(errors)
        }
    )

还有一个评论,您是否需要所有这些复杂性来进行简单检查,我不知道您的其余代码和构造,但正如建议将按钮的状态作为道具传递(如上)和只需在组件本身内处理 isFavorited 调用,因此不需要为这个简单的请求使用存储?

编辑 2:

如果您需要返回另一种方式与 promise try::

Vue.$http.post(window.Laravel.baseUrl+'/member/store/favorite/check-favorite', favorite)
  .then((response) => {
      console.log('success')
      resolve(response.data);// replace the return with resolve?
  }, (response) => {
       console.log('success');
        console.log(response);
    reject(response.data);// replace the return with reject?
  });

可能是问题??

【讨论】:

  • 我这样做:var res = this.$store.dispatch('checkFavoriteStore', payload);console.log(res);。结果:postimg.org/image/grd6mqe4n。响应应该显示exist 还是no_exist
  • 可以添加store调用,这样曾经使用过的代码就叫做checkFavoriteStore,所以我们可以看到你用来返回的代码,因为这是一个Promise,所以需要看看它是如何构造的跨度>
  • 您是否添加了 RETURN,因为我有 return favorite.checkFavorite,如果您仍然得到承诺,您可能需要在 Vue.http.post 中使用 resolve() 而不是 return 和reject() 在错误中,也将其添加到上面以便您可以看到?
  • Vue.$http... 之前也需要return
【解决方案2】:

下面是一个不需要商店的解决方案,只是一个想法可能会很方便:

PHP 页面:

    <favorite-button 
        :storeid="{{$storeid}}" 
        :favorited="{{$isFavorited}}"
        :url="{{route('check-favorite')}}"
    ></favorite-button>

    <script>
        (function(){
            import favoriteButton from 'favorite-button';
            new Vue({
                el : '#app',
                components : {
                    favoriteButton
                }
            });
        })();
    </script>

然后是组件

    <style lang="sass">
        .heart {
            color: grey;
            &.is-favorited {
                color: red;
            }
        }
    </style>
    <template>
        <button class="btn btn-block btn-success" @click.prevent="udateFavorited($event)">
            <span class="heart" :class="{'is-favorited' : this.favorited }">&heart;</span>&nbsp;<span :text="{this.favoriteText}"></span>
        </button>
    </template>
    <script>
        import axios from 'axios';
        export default{
            props : {
                storeid : {
                    type: Number,
                    required : true,
                    default : () => {}
                },
                favorited : {
                    type: Boolean,
                    required : false,
                    default : false
                },
                url : {
                    type: String,
                    required : true
                }
            },
            computed : {
                favoriteText : function(){
                    return (this.favorited) ? 'Unfavorite' : 'Favorite';
                }
            },
            methods:{
                updateFavorited(event){
                    //-- so update the db so if fasle update to true else if true = false
                    axios.post(this.url, this.storeid)
                        .then(response => {
                            //-- all ok update the visual button
                            this.favorited = response.data.favorited
                        })
                        .catch(error => {
                            console.log('error');
                            console.log(error);
                            this.favorited = response.data.favorited
                    });

                }
            }
        }


    </script>

所以基本上在初始加载页面时,它会传递storeid,以及商店是否已经收藏,以及点击事件的url操作

然后当用户点击用户点击按钮时,它将更新数据库,然后是文字和心脏的颜色,具体取决于结果

如果有问题要考虑另一个想法/解决方案??

【讨论】:

    猜你喜欢
    • 2017-06-30
    • 2017-11-08
    • 1970-01-01
    • 2019-12-01
    • 1970-01-01
    • 2019-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多