Vuejs提取请求返回数据,但属性分配不起作用 [英] Vuejs Fetch Request returns data but attributes assignments don't work

查看:88
本文介绍了Vuejs提取请求返回数据,但属性分配不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的项目中,我正在使用Vuejs.我在其他项目及其工作中使用了相同的技术.但是在这里,我无法将获取请求返回的数据分配给json资源.

I am playing around with Vuejs in our project. I have used the same technique in my other project and its working. But here I am not able to assign the data return by the fetch request to a json resource.

当我尝试访问返回的数据并将其置于警告状态时,确实为我提供了数据对象.但我想将其分配给我的数据属性包数组.

When I try to access data returned in then and put it in alert it does gives me the data objects. but I want to assign it to my data attribute packages array.

这是我的组件代码

<template>
 <div id="packages">
    <div class='radio' v-for="package in packages">
        <label>
            <input type='radio' name='packageradio' v-bind:value="package.id">{{ package.quantity }}
            <span id='price-tag'>{{ package.price }}</span>
        </label>
    </div>
 </div>
</template>
<script>
export default {
    data(){
        return {
            packages:[]
        }
    },
    created(){
        this.fetchPackages();
    },
    methods: {
        fetchPackages: function(){
            fetch('/die-cut/size/4/packages')
                .then(res => res.json())
                .then(function(res){
                    alert("i am hit");
                    this.packages = res;
                })
                .catch(err => console.log(err));
        }
    }
}
</script>

这是api:

[
{
"id": 1,
"quantity": 50,
"price": 400,
"saving": 100,
"size_id": 4,
"sticker_id": 2,
"created_at": "2018-02-21 17:48:46",
"updated_at": "2018-02-21 17:48:46"
},
{
"id": 2,
"quantity": 100,
"price": 900,
"saving": 100,
"size_id": 4,
"sticker_id": 2,
"created_at": "2018-02-21 17:50:43",
"updated_at": "2018-02-21 17:50:43"
}
]

推荐答案

我认为这与您的this关键字有关,因此,请使用ES5语法或执行类似的操作

I think its to do with your this keyword so, either use the ES5 syntax or do some thing like this

fetchPackages: function(){
       var vm = this
        fetch('/die-cut/size/4/packages')
            .then(res => res.json())
            .then(function(res){
                alert("i am hit");
                vm.packages = res;
            })
            .catch(err => console.log(err));
    }

或者当然,您可以继续执行类似的操作

Or off course you can go ahead and do something like this,

fetchPackages(){
        fetch('/die-cut/size/4/packages')
            .then(res => res.json())
            .then((res) => {
                alert("i am hit");
                this.packages = res;
            })
            .catch(err => console.log(err));
    }

这篇关于Vuejs提取请求返回数据,但属性分配不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆