【问题标题】:How to push Object element to an array in Vuejs/Javascript如何在 Vuejs/Javascript 中将 Object 元素推送到数组中
【发布时间】:2017-12-11 21:05:30
【问题描述】:

我正在尝试在VueJs 中构建一个小型应用程序, 以下是我的数据集:

data(){
    return {
        pusher: '',
        channel:'',
        notify: [],
        notifications: '',
        notificationsNumber: '',
    }
},

我在组件的 created 属性中有一个 axios 调用:

axios.get('api/notifications', {headers: getHeader()}).then(response => {
    if(response.status === 200)
    {
        this.notify = response.data.notifications
        this.notificationsNumber = this.notify.length
    }
}).catch(errors => {
    console.log(errors);
})

我已经实现了pusherJs,所以我有以下代码:

this.pusher = new Pusher('xxxxxxxx', {
    cluster: 'ap2',
    encrypted: true
});

var that = this
this.channel = this.pusher.subscribe('stellar_task');
this.channel.bind('company_info', function(data) {
    console.log(data.notification);
    that.notifications = data.notification
});

一旦从推送器获取值,我想将它推送到我的数组通知作为监视属性,如下所示:

watch: {
    notifications(newValue) {
        this.notify.push(newValue)
        this.notificationsNumber = this.notificationsNumber + 1
    }
}

所以问题是我通过推送器接收的数据格式是对象形式,并且推送功能没有在此实现:

截图:

帮我解决这个问题。

【问题讨论】:

  • 你能在console.log(this.notify) 里面watch 吗?如果是array,则必须有push
  • @morgh 是对的,this.notify 看起来不像是一个数组。
  • @MatWaligora 我已经将它定义为数据集中的一个数组,顺便说一句,我不知道发生了什么,但是在执行 console.log 时我得到了答案。
  • @morgh 我做了 console.log 并且它正在工作。即使我删除了 console.log() 它现在正在工作,在加载组件期间可能是一些监视功能错误。现在一切顺利。

标签: javascript vue.js vuejs2


【解决方案1】:

我假设response.data.notifications 是一个类似对象的数组

所以你要做的就是:

this.notify = [...response.data.notifications];

【讨论】:

    猜你喜欢
    • 2022-06-15
    • 1970-01-01
    • 2017-06-17
    • 2021-11-06
    • 1970-01-01
    • 2015-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多