[Vuejs]-How to call a method from vue template with get data

0👍

Please change your code to this:

<script>
export default {
    data(){
        return {
            products: []
        };
    },
    methods:{
                getProducts:function(storeID){            
                    axios.get('/axios/storeproducts/'+storeID, {
                        params: {
                            storeID: storeID,
                        }
                    })
                    .then(function (response) {
                        console.log(response.data);
                       this.products = response.data;
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
                }
            },
    },
    mounted(){
        //this shoud call after load the 'store.id';
        this.getProducts(this.store.id);
    }
}
</script>

and template to:

<ul>
    <li v-for="product in products" :key="product.id">{{product.id}}</li>
</ul>

0👍

A more subtle approach to using methods via async in a template is this

  1. in the created/mounted function call your method – this is useful for async calls

    <script>
    export default {
    data: function(){
    return {
    products: []
    }
    },
    created: function(){
    // make async request here or in mounted
    this.getProducts();
    },
    methods:{
    getProducts:(){
    //Get store id via props or route query or params
    axios.get('/axios/storeproducts/'+storeID, {
    params: {
    storeID: storeID,
    }
    })
    .then(function (response) {
    console.log(response.data);
    this.products = response.data;
    })
    .catch(function (error) {
    console.log(error);
    });
    }
    }
    }
    </script>

  2. Finally, use the property in template

    <ul>
    <li v-for="product in products" :key="product.id">{{product.id}}</li>
    </ul>

Hope this helps

Leave a comment