简体   繁体   中英

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

By checkFavoriteStore method, it will call action on the vuex store

And the results will return the response

How to I get the response?

UPDATE

My action on the vuex store like this :

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 :

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

  <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

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:

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. let's see if this helps?

also try adding a return in front of, as it needs to return to its original caller

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

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

    <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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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