微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Vue计算数组附加值而不是重写

如何解决Vue计算数组附加值而不是重写

我有一个名为contactDetails的数组,其中包含用户的不同联系人列表(例如电话号码,社交媒体句柄等)。可用的联系人平台已在列表中预定义。我有一个计算值,可以跟踪用户尚未添加为联系方式的平台。计算的数组用于选择字段中,供用户在创建新的联系人详细信息时选择。

new Vue({
    el: '#app',data() {
        return {
            platforms: [
                {
                    text: 'WhatsApp',value: 1,},{
                    text: 'Call',value: 2,{
                    text: 'Email',value: 3,{
                    text: 'LinkedIn',value: 4,{
                    text: 'TikTok',value: 5,{
                    text: 'Twitter',value: 6,],contactDetails: [],onAddContactDetails() {
            var selectedplatform = this.platforms.find(obj => {
                return obj.value == this.platformId
            })

            var newContact = {
                platform: selectedplatform.value,platformName: selectedplatform.text,channel: this.channel,priority: this.contactPriorityId
            }
            this.contactDetails.push(newContact)
            this.updatePriority(newContact,this.contactDetails)

            this.platformId = null
            this.contactPriorityId = null
            this.channel = null

            this.platformlist = null;
            this.isAddContact = false;
        },computed: {
            platformlist() {
                var list = [];
                if (this.contactDetails.length == 0) {
                    return this.platforms;
                } else {
                    list = this.platforms;
                    for (var i = 0; i < this.contactDetails.length; i++) {
                        var id = this.contactDetails[i].platform;
                        for (var j = 0; j < this.platforms.length; j++) {
                            if (this.platforms[j].value == id) {
                                list.splice(j,1)
                            }
                        }
                    }
                }
                return list;
            },

Before adding a contact detail

这是添加新的联系人详细信息之前下拉列表的外观。

但是,我的计算属性会更新,但不是刷新列表,而是将新列表附加到现有选项上,从而导致重复。

After adding a new contact detail

原始列表+新的联系人详细信息列表应该是(完整列表-用户添加的联系人)

我想知道如何解决此问题,以及是否有更好的方法来设置下拉菜单中留给用户的可用选项。谢谢!

解决方法

您正在对计算所得的属性中的this.platforms进行突变;如果要对其进行突变,则应该先克隆它:

list = this.platforms.slice()

我不确定是什么原因导致重复。您只会推向contactDetails并从platforms中撤出。

您的计算属性可以大大简化:

computed: {
  platformList() {
    // Filter platforms
    return this.platforms.filter(platform =>
      // Include this platform if there is no contact detail using that platform
      !this.contactDetails.some(contact =>
        contact.platform === platform.value
      )
    )
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。