从VueJS mixin访问常量

时间:2018-10-16 02:04:35

标签: vue.js mixins

我有这个组成部分

<script>
const serviceName = 'events'

import { mapState } from 'vuex'

import crud from './mixins/crud'

export default {
    mixins: [crud],

    data() {
        return {
            serviceName: serviceName,

            apiBaseUri: '/api/v1/' + serviceName,
        }
    },

    computed: {
        ...mapState({
            events: state => state.events.data,
        }),
    },

    mounted() {
        this.boot()
    },
}
</script>

它定义了一个serviceName,我还需要在此原始混合中使用它:

import { mapActions, mapMutations, mapState } from 'vuex'

export default {
    data: function() {
        return {
            loading: {
                environment: false,

                table: false,
            },
        }
    },

    computed: {
        ...mapState({
            form: state => state.events.form,
            environment: state => state.environment,
        }),
    },

    methods: {
        ...mapActions(serviceName, ['load']),

        ...mapMutations(serviceName, [
            'setDataUrl',
            'setStoreUrl',
            'setErrors',
            'setFormData',
            'storeFormField',
        ]),

        isLoading() {
            return this.loading.environment || this.loading.table
        },

        boot() {
            this.setDataUrl(this.apiBaseUri)

            this.setStoreUrl(this.apiBaseUri)

            this.load()
        },

        back() {
            this.$router.back()
        },

        storeModel() {
            this.store().then(() => {
                this.load()

                this.back()

                this.clearForm()
            })
        },
    },
}

问题是由于总是在mapActions()和mapMutations()中使用serviceName,所以我总是收到“未定义serviceName”错误消息。

错误发生在

import crud from './mixins/crud'

它完全忽略了我也尝试过的诸如window.serviceName之类的东西。

1 个答案:

答案 0 :(得分:1)

我能想到的最简单的解决方案是将serviceName定义移至另一个文件。例如...

// constants.js
export const SERVICE_NAME = 'events'

然后您可以在需要的地方导入它,例如

// in your component, your mixin, etc
import { SERVICE_NAME as serviceName } from './constants'