代码之家  ›  专栏  ›  技术社区  ›  Antonio Carlos Ribeiro

从VueJS mixin访问常量

  •  0
  • Antonio Carlos Ribeiro  · 技术社区  · 6 年前

    我有这个组件

    <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,我需要在这个crud mixin中使用它:

    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()
                })
            },
        },
    }
    

    问题是,我总是收到一条“servicename is not defined”错误消息,因为servicename在mapactions()和mapmutations()中使用。

    错误发生在

    import crud from './mixins/crud'
    

    它完全忽略了window.servicename之类的东西,我也试过了。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Phil Moon    6 年前

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

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

    然后您可以在需要时导入它,例如

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