如何从vue.js中的另一个组件更新一个组件

时间:2017-01-27 07:01:31

标签: vue.js

我有网络应用,其中界面基于vue.js 2.0。

我有基于select2插件显示输入的组件。

默认显示所选选项,但当用户点击它时,我会显示select2以允许用户修改选项。

代码如下所示:

<template>
<div @click="toggleEdit">
    <span v-show="isEnabled">
        <select
            class="form-control"
            :name="name"
            :multiple="multiple"
        >
            <option v-for="opt in options" :value="opt.id"> {{ opt.text }} </option>
        </select>
    </span>
    <span v-show="!isEnabled">
        <div v-if="selectedOptions.length === 0">
            {{ emptyText }}
        </div>
        <div v-for="opt in selectedOptions">
            {{ opt }}
        </div>
    </span>
</div>
</template>
<script>
export default {
    props: {
        options: {
            type: Array,
            required: false,
            default: function() {
                return []
            }
        },
        name: {
            required: true,
            type: String
        },
        multiple: {
            required: false,
            type: Boolean,
            default: false
        },
        emptyText: {
            required: false,
            type: String,
            default: ""
        },
        sourceUrl: {
            required: false,
            type: String,
            default: ""
        },
        enabled: {
            required: false,
            type: Boolean,
            default: false
        }
    },

    data() {
        return {
            isEnabled: this.enabled
        }
    },

    watch: {
        options: {
            handler: function() {
                console.log(arguments)
            },
            deep: true
        }
    },

    mounted: function() {
        this.select = $(this.$el).find("select");
        this.select.select2();
        var that = this;
        this.select.on("change", function(e) {
            var indexMap = {};
            for(var i = 0; i < that.options.length; i++) {
                that.options[i].selected = false;
                indexMap[that.options[i].id] = i;
            }
            var selected = that.select.select2('val');
            if(typeof selected === "string") {
                selected = [selected];
            }
            for(var i = 0; i < selected.length; i++) {
                var index = indexMap[selected[i]];
                console.log(index)
                console.log(selected[i])
                if(index !== undefined) {
                    var option = that.options[index];
                    option.selected = true;
                    that.$set(that.options, index, option);
                }
            }
        })
        this.select.on("select2:open", function() {
            that.isEnabled = true;
        });
        this.select.on("select2:close", function() {
            that.isEnabled = false;
        });
    },
    methods: {
        toggleEdit() {
            if(this.isEnabled) return; // to pass select2 clicks
            this.isEnabled = !this.isEnabled;
            var that = this;
            this.$nextTick(function() {
                that.select.select2("open");
            });
        }
    },
    computed: {
        selectedOptions: function() {
            console.log(this.options)
            return this.options.filter(function(option) {
                console.log(option.selected);
                if(option.selected === true) return true;
                return false;
            });
        }
    }
}

问题是:我想使用此组件显示多个不同的selects。 Name属性可以是以下之一:model1[field1]model1[field2],...,model40[field1],...,model99[field15],其中每个modelN对应于数据库中的表它的各个领域。

当用户更改选项时,必须将ajax请求发送到服务器,服务器返回json-object,如下所示

{
   "errorText": null or "text with error",
   "disableFields": ["model3[field4]", "model24[field15]"]
}

我想解析&#34; disableFields&#34;数组并禁用this组件another组件。

实现此目的的一种方法(伪代码):

foreach field in disableField:
    $(document).trigger("disableField" + field);

mounted组件的this方法

var self = this;
$(document).on("disableField" + this.name, function() {
    self.isEnabled = false
})

如果没有父组件,有没有更好的方法呢?

3 个答案:

答案 0 :(得分:15)

不允许直接与其他组件通信。您可以使用父组件在组件之间进行通信,或some kind of event bus

var bus = Vue()

组件A发出事件,而组件B可以捕获它,反之亦然。

// component A
bus.$emit('cool_event_name', interesting_data)

// component B
bus.$on('cool_event_name', function(interesting_data) {
   console.log(interesting_data)
})

答案 1 :(得分:13)

您可以使用this.$root而不使用全局变量:

// component A emits an event
export default {
  name: 'A',
  methods: {
    buttonClicked: function () {
      this.$root.$emit('myEvent', 'new message!');
    }
  }

// component B catch your event
export default {
  name: 'B',
  data () {
    return {
        message: 'Old message!'
    }
  },
  mounted: function () { 
    this.$root.$on('myEvent', (text) => { // here you need to use the arrow function
     this.message = text;
    })
  }
}

答案 2 :(得分:0)

要实现你想要实现的目标并不容易,因为你的帖子太长而且那里有太多的东西,但我会尝试。如果遗漏了某些内容,只需发表评论,我会尝试编辑以帮助您更好。

禁用字段

我建议将此数组放在父组件的data中(例如,包含整个表单/页面的组件),然后将其传递到<component-instance :disabled='disabled.componentId'>等字段请注意:disabled 。数据绑定将使您与父数据保持同步(这意味着您的父disabled.componentId中的每个更改都将反映在您的子组件中)

解析'已禁用'JSON

我认为这是非常直接的,因为您只需将返回的字段分配给data: { disabled },但如果您无法弄明白 - 请告诉我们。

**组件之间的其他通信方式**

如果要从CHILD组件更新PARENT,则必须使用VUE事件总线或事件处理程序来使用EVENT。 在子组件上,如果不需要从子组件传递特殊数据或在子组件中创建自定义事件表示器,则可以使用<child-component @click='yourParentMethod()'>

// child component
methods: {
someMethod() => {
this.emit('customEvent', someData)
}
}

//parent component
<child-component @customEvent='customEventHandler(dataFromChild)'> 

希望它有所帮助。

相关问题