拥有这样的组件:
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?
答案 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;
}
}