在导入的对象中访问VM

时间:2017-06-14 10:39:34

标签: javascript ecmascript-6

拥有这样的组件:

import { someData } from 'someData.js'

export default {
    data() {
        return {
            foo: 'bar',
            someData: someData
        }
    }
}

someData.js:

export const someData = {
    someObject: {
        test: this.foo // How can I access foo from the component, where this object is imported from? This is not accessable.
    },
}

如何在someData.js中访问this.foo?

2 个答案:

答案 0 :(得分:0)

您可以改为导出函数,并将该值作为参数传递:

import { getSomeData } from 'someData.js'

export default {
    data() {
        return {
            foo: 'bar',
            someData: getSomeData('bar')
        }
    }
}

someData.js

export const getSomeData = foo => ({
    someObject: {
        test: foo
    },
})

答案 1 :(得分:0)

这是不可能的,someData对象是在调用data()方法之前构造的。您还需要将其设为函数,并接受foo作为参数:

export function makeSomeData(foo) {
    return {
        someObject: {
            test: foo
        },
    };
}

import { makeSomeData } from 'someData.js'

export default {
    data() {
        return {
            foo: 'bar',
            someData: makeSomeData(this.foo)
        }
    }
}

这仍然不能与Self-references in object literal declarations完全一致。您将需要使其成为getter函数,或者在使用foo属性构造对象后调用它:

export default {
    data() {
        var obj = {
            foo: 'bar',
        };
        obj.someData = makeSomeData(obj.foo);
        return obj;
    }
}