0

Having a component like so:

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.
    },
}

How can I access this.foo in someData.js ?

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
Qar
  • 1,746
  • 3
  • 17
  • 24
  • I don't think it's possible. What do you need this for? – Michał Perłakowski Jun 14 '17 at 10:44
  • The component is fetching some analytics data. The someData.js is a highcharts configuration object, that needs to fetch those analytics data, from a computed property in the component. – Qar Jun 14 '17 at 10:46

2 Answers2

0

You can export a function instead, and pass the value as an argument:

import { getSomeData } from 'someData.js'

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

someData.js

export const getSomeData = foo => ({
    someObject: {
        test: foo
    },
})
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
0

That's not possible, the someData object is constructed before the data() method will be called. You will need to make it a function as well, and accept the foo as a parameter:

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

import { makeSomeData } from 'someData.js'

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

That still doesn't exactly work with Self-references in object literal declarations. You will either need to make it a getter function, or invoke it after constructing the object with the foo property:

export default {
    data() {
        var obj = {
            foo: 'bar',
        };
        obj.someData = makeSomeData(obj.foo);
        return obj;
    }
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375