【问题标题】:How to add and item to an Array using Vue JS?如何使用 Vue JS 向数组添加和项?
【发布时间】:2016-06-16 06:16:44
【问题描述】:

我正在使用 VUE JS,但由于某种原因,我没有在视图上显示新项目。如果我使用 push 方法,什么都不会发生。如果我使用 this.$set('productos',producto) 会显示该项目,但是当我尝试将另一个项目推送到数组时,前一个项目会被删除。

new Vue({


    el: '#ticket',

    data:{
        newCodigo:{
            codigo: '',
        },

        productos:[],

    },



    computed:{
        errors: function(){
            for(var key in this.newCodigo){
                if(! this.newCodigo[key])
                    return true;
            }
            return false;
        }
    },


    methods:{

        addProducto: function(){
            var codigo = this.newCodigo;
            this.$http.post('/api/addProducto', codigo).success(function(producto){

                this.productos.push(producto);
                //this.$set('productos',producto);
            });
        }
    }
});

我能够从数据库中检索数据,但它没有显示在视图上。

<div class="container">
<div class="row">
    <div id="ticket">
        <form action="POST" v-on:submit.prevent="addProducto">
            <input type="hidden" name="_token" id="token" value="{{ csrf_token() }}" > 
            <div class="form-group">
                <label for="Codigo">
                    Escanea:
                    <span class="error" v-if="! newCodigo.codigo">*</span>
                </label>
                <input type="text" name="codigo" id="codigo" class="form-control" v-model="newCodigo.codigo">
            </div>
        </form>
        <article v-for="producto in productos" :data="productos">

            <h3>@{{producto.descripcion}}</h3>

            <h3>@{{producto.precio}}</h3>
        </article>
    </div>
</div>

【问题讨论】:

    标签: laravel-5.2 vue.js


    【解决方案1】:

    在你的 ajax 调用的回调函数中,this 不指向 vm 实例。只需将其更改为:

    this.$http.post('/api/addProducto', codigo).success(function (producto) {
        this.productos.push(producto);
    }.bind(this));
    

    【讨论】:

    • 感谢您的回答。我尝试了绑定,但仍然没有显示在

      @{{producto.descripcion}}

      @{{producto. precio}}

    猜你喜欢
    • 2021-03-24
    • 2017-05-13
    • 2019-04-04
    • 2019-01-22
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多