如何从具有获取数据的vue模板中调用方法

问题描述 投票:0回答:2

我在Vue中创建了一个方法,在模板中调用此方法,然后在console.log中显示数据,但未在模板中获取数据。

我的Vue方法:

<script>
export default {
    methods:{
        getProducts:function(storeID){            
            axios.get('/axios/storeproducts/'+storeID, {
                params: {
                    storeID: storeID,
                }
            })
            .then(function (response) {
                console.log(response.data);
               return response.data;
            })
            .catch(function (error) {
                console.log(error);
            });
        }
    },
}
</script>

我的模板:

<ul>
    <li v-for="product in getProducts(store.id)" :key="product.id">{{product.id}}</li>
</ul>
laravel vue.js
2个回答
0
投票

请将该代码更改为此:

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

和模板至:

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

0
投票

在模板中通过异步使用方法的更微妙的方法是这个

  1. 在创建/安装的函数中调用您的方法-这对于异步调用很有用

    <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. 最后,使用模板中的属性

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

希望这会有所帮助

© www.soinside.com 2019 - 2024. All rights reserved.