如何从 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 attribute can be one of the following: model1[field1] , model1[field2] , …, model40[field1] , …, model99[field15] , where每个 modelN 对应于数据库中的表及其各自的字段。

当用户更改选项时,必须将 ajax 请求发送到服务器,服务器返回这样的 json-object

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

我想解析“disableFields”数组并禁用 this 组件 another 组件。

完成此操作的一种方法(伪代码):

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

而在 mounted 方法中 this 组件

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

如果没有父组件,有没有更好的方法来做到这一点?

原文由 Jackson J 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 576
2 个回答

不允许直接与另一个组件通信。您可以使用父组件在组件或 某种事件总线 之间进行通信。

 var bus = new 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)
})

另一种解决方案可能是使用 $root 可以从 Vue 实例的所有子组件访问它。这节省了全局总线的定义(如上)。请注意, 不建议 将此方法作为通用方法,它更像是对某些边缘情况的解决方案。

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

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

原文由 Nicolas Heimann 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以使用 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;
    })
  }
}

原文由 qqus 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题