我有一个.vue单个文件组件,它有太多行,所以我试图将它分成.js文件。我可以在这个thread的帮助下实现这一目标。
但是,当我尝试使用不同文件中的变量时,我仍然陷入困境。
所以,这就像旧的foobar.vue
看起来像
foobar.js
<script>
let foo; // there is one global variable (somehow I have to do this way)
export default {
data() {
return {
bar: [1, 2, 3, 4],
}
},
methods: {
baz() {
foo = 'some text';
this.bar.push(5);
},
qux() {
foo += 'lorem ipsum';
this.bar.shift(0);
},
}
}
</script>
现在,我分成两个文件,qazxsw poi,qazxsw poi,它们看起来像这样:
foobar.vue
baz.js
baz.js
qux.js
qux.js
<script src="@/baz.js"></script>
<script src="@/qux.js"></script>
<script>
import { baz } from '@/baz';
import { qux } from '@/qux';
let foo; // I want to manipulate this from external files
export default {
data() {
return {
bar: [0, 1, 2, 3], // I also want to manipulate this from external files
}
},
methods: {
baz,
qux,
}
}
</script>
显然,它不起作用,因为function baz() {
foo = 'some text'; //foo undefined
this.bar.push(5); //this.bar undefined
}
export { baz };
和function qux() {
foo += 'lorem ipsum'; // foo undefined
this.bar.shift(0); //this.bar undefined
}
export { qux };
看不到baz()
和qux()
(在foo
)。那么,为了能够看到和操纵this.bar
和data()
,我该怎么做?
谢谢!
使用foo
- 在全局范围内存储变量
或者添加bar
文件并添加:
window.foo
并在baz.js和qux.js中导入它们
common.js
好吧,Vue提供export var foo;
实例来访问全局级别的变量和方法。此外,实例也是反应性的。
假设你的两个组件import { foo } from "./common.js"
和$root
都绑定到名为foo
的主要组件。
现在在bar
组件的数据对象中定义一个变量。
要从App
组件访问数据,您可以从Vue的App
访问它。
App
$root
注意:$ root与.vue文件一起使用
希望这可以帮助!
你应该看看const Foo = {
template: '<span> {{this.$root.foo}} {{this.$root.from}} </span>'
};
const Baz = {
template: '<span> {{this.$root.baz}} {{this.$root.from}} </span>'
};
new Vue({
el: '#app',
data: {
foo: 'Foo',
baz: 'Baz',
from: 'from app component'
},
components: {
Foo,
Baz
}
})
。
这是一个可以尝试的简单示例:
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<Foo></Foo>
<br />
<Baz></Baz>
</div>