简体   繁体   English

如何在vue.js 2上获得响应ajax?

[英]How to get response ajax on the vue.js 2?

My code is like this : 我的代码是这样的:

<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>

When the script executed, it will call checkFavoriteStore method first 执行脚本后,将首先调用checkFavoriteStore方法

By checkFavoriteStore method, it will call action on the vuex store 通过checkFavoriteStore方法,它将在vuex存储上调用action

And the results will return the response 结果将返回响应

How to I get the response? 我如何得到回应?

UPDATE UPDATE

My action on the vuex store like this : 我对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
}

And the api like this : 和这样的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)
        );
    }
}

if your returning a result then assign the call to a variable so tyr: 如果返回结果,则将调用分配给变量,这样:

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

then you can get access to the response via the var res . 然后您可以通过var res访问响应。 I believe the events will return it back to you 我相信这些事件会把它还给您

MORE query: 更多查询:

just a little question on this. 对此只是一个小问题。

If your getting the store ID and passing this to the component as a prop. 如果您获得商店ID并将其作为道具传递给组件。 So surely you could also pass in another prop that tells if the store has already been liked? 因此,您当然也可以传递另一个道具来告诉商店是否已被喜欢? So getting this data via the db call to the view, thus saving having to do a check after its loaded, so something like: 因此,通过对视图的db调用获取此数据,从而省去了在加载后进行检查的麻烦,例如:

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

So using the favorited property to change the button accordingly?, so need for the checkFavoriteStore call and saving time on additional http request etc 因此,使用favourited属性来相应地更改按钮吗?,因此需要进行checkFavoriteStore调用并节省其他HTTP请求的时间等

Don't know your code or what's its doing etc but just a thought?? 不知道您的代码或代码在做什么,只是一个想法?

EDIT AFTER ADDITION INFO ADDED 添加后添加信息

OK so can you change your http request to say: 确定,所以您可以更改您的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;
  });

i have added console.logs so we can see whats happing. 我添加了console.logs,所以我们可以看到有什么变化。 let's see if this helps? 让我们看看这是否有帮助?

also try adding a return in front of, as it needs to return to its original caller 还要尝试在其前面添加一个return,因为它需要返回其原始调用者

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

Also a comment, do you need all this complexity for just this simply check, i don't know the rest of your code and construction, but as suggested passing in the state of the button as a prop (as above) and just handle the isFavorited call within the compnent itself, so no need to use a store fo this simple request?? 还有一条评论,您是否需要所有这种复杂性来进行简单的检查,我不知道您的其余代码和构造,但是建议将按钮的状态作为道具传递(如上),然后处理组件本身内部的isFavorited调用,因此无需使用此简单请求的存储库?

EDIT 2: 编辑2:

if you need to return another wahy with 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?
  });

Might be the issue?? 可能是问题所在??

below is a solution that does not require a store, just a thought might be handy: 以下是不需要商店的解决方案,只需考虑一下即可:

PHP Page: 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>

Then the component 然后是组件

    <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>

So basically on initial loading the page, it passes the storeid, and whether the store is or not already favorited, as well as the url action on click event 因此,基本上在最初加载页面时,它会传递storeid,是否存储已被收藏以及click事件的url操作

Then when a user clicks the user clicks the button it will update the DB and then the text and the colour of the heart, depending on the result 然后,当用户单击时,用户将单击按钮,它将更新数据库,然后更新文本和心脏的颜色,具体取决于结果

Just another idea/solution to consider if having issues?? 还有问题要考虑的另一个想法/解决方案?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM