Vue:以vuex存储状态导入对象

时间:2019-02-27 12:20:28

标签: vuejs2 vuex

我正在将各种设置添加到vuex存储中,并通过各种组件进行使用和更新。 这些设置细分为对象,但是store.js文件变得很长,是否有任何方法可以从独立文件中导入这些对象,因此概览更加清晰,每个设置都可以有自己的文件?

export const store = new Vuex.Store({
    state: {

        // @import settings1 from 'settings1.js'
        // @import settings2 from 'settings2.js
        // @import settings3 from  'settings3.js
        // ...

        // instead of adding objects like this:
        settings1: {
            name1: value1,
            name2: value2,
            name3: value3,
            // ...
        },
        settings2: {
            name1: value1,
            name2: value2,
            name3: value3,
            // ...
        },
        settings3: {
            name1: value1,
            name2: value2,
            name3: value3,
            // ...
        }
    }
});

2 个答案:

答案 0 :(得分:1)

我认为这与普通js中的工作原理相同,并且如下所示:

import settings1 from './settings1'
import settings2 from './settings2'
import settings3 from  './settings3'

export const store = new Vuex.Store({
    state: {
        settings1,
        settings2,
        settings3
    }
});

答案 1 :(得分:1)

您将导出对象以插入到父对象中。

import settings1 from './settings1'
import settings2 from './settings2'

// or 

const settings1 = require('./settings1')
const settings2 = require ('./settings2')

export const store = new Vuex.Store({
    state: {settings1,settings2}
});

settings1.js

module.exports = {
   value1: 1,
   value2: 2,
}

// or even better if using `import` instead of `require`

export default {
   value1: 1,
   value2: 2,
}

settings2.js

module.exports = {
   value3: 2,
   value4: 4,
}

// or even better if using `import` instead of `require`

export default {
   value3: 3,
   value4: 4,
}