Vuejs Fetch Request返回数据,但属性赋值不起作用

时间:2018-03-11 07:38:38

标签: laravel api vue.js

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

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

这是我的组件代码

<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"
}
]

2 个答案:

答案 0 :(得分:0)

包的数据应该正常工作。我在你的代码中看到的问题是使用以下html:

<label>
   <input type='radio' name='packageradio' v-bind:value="package.id">
   {{ package.quantity }}
   <span id='price-tag'>{{ package.price }}</span>
</label>

来自documentation的标签元素:

  

label可以允许Phrasing content,但不允许使用后代标签元素。不允许使用标记控件以外的可标记元素。

因此,在代码中input,流内容是关键问题。

您的代码存在问题:

.then(function(res){
   alert("i am hit");
   this.packages = res; 
   // this isn't referenced to the vue instance from the function scope
 })

替换为:

.then(res => { // access parent scope
   alert("i am hit");
   this.packages = res; // now, this will access the vue instance
 })

答案 1 :(得分:0)

我认为这与你的关键字有关,所以要么使用ES5语法,要么做这样的事情

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));
    }

或者当然,你可以继续做这样的事情,

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));
    }