Как вызвать метод из шаблона vue с получением данных - PullRequest
0 голосов
/ 28 января 2020

Я создаю метод в 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>

Ответы [ 2 ]

0 голосов
/ 28 января 2020

Более тонкий подход к использованию методов через asyn c в шаблоне заключается в следующем:

  1. в вызове созданной / смонтированной функции вашего метода - это полезно для asyn c звонки

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

Надеюсь, это поможет

0 голосов
/ 28 января 2020

Пожалуйста, измените ваш код на:

<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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...