子组件的Vue 2触发方法

时间:2017-11-19 14:19:23

标签: vuejs2

如果我可以触发和事件,或者在用户对象更新时调用vue-button组件中的方法,我将很高兴。我需要确保这只发生在这个特定的vue按钮上,而不是在页面上的任何其他按钮上。

该按钮控制一个状态对象,该状态对象根据服务器的响应设置按钮的样式。如果返回错误响应,将显示红色;如果返回成功响应,则显示绿色在以太网情况下,该按钮也被禁用,因此用户不能垃圾邮件点击它。我需要能够在用户更新时从父级重置按钮。

我不相信全局事件总线是解决方案,因为我需要对哪些组件响应事件进行精细控制,并且该按钮在很多地方使用。

<template>
    <div class="row">
        <div class="col-12">
            <basic-input-field :resource="user" :set-resource="setUserProperty" property="name" label="Name"></basic-input-field>
            <basic-input-field :resource="user" :set-resource="setUserProperty" property="email" label="Email"></basic-input-field>
            <basic-input-field :resource="user" :set-resource="setUserProperty" property="password" label="Password"></basic-input-field>

            <vue-button :on-click="updateUser" label="Save"></vue-button>
        </div>
    </div>
</template>

<script>
    import axios from 'axios';
    import basicInputField from '../general/forms/basic-input-field.vue';
    import vueButton from '../general/buttons/vue-button.vue';

    export default {
        name: 'user',
        data() {
            return {
            };
        },
        mixins: [],
        components: {
            basicInputField,
            vueButton
        },
        computed: {
            user() {
                return this.$store.state.user;
            },
        },
        mounted() {
            this.$httpGet('user', {id: 5});
        },
        watch: {
            'user': function (newUser) {
                // I want to trigger an event inside the component vue-button
                // I do not want to trigger then event in every vue-button component on the page just this vue-button
                // I need to call a resetStatus method within the vue-button component when the user changes
                // This would have worked in vue 1 with an event 'resetStatus' that would call the method in the vue-button component
                this.$broadcast('resetStatus');
            }
        },
        methods: {
            setUserProperty(property, value) {
                this.$store.commit('UPDATE_MODULE_RESOURCE', {module: 'user', resource: property, value: value});
            },
            updateUser() {
                return this.$httpPut('user', {id: this.user.id}, this.user);
            }
        },
    };
</script>

0 个答案:

没有答案