Vue.js加载单文件组件 [英] Vue.js loading single-file components
问题描述
我是Vue.js的新手,想要使用单文件组件,但我不了解工作流程。
I'm new to Vue.js and want to use single-file components, but I don't understand the workflow.
例如,我有三个组件: App
, Grid
和列表
For example, I have three components: App
, Grid
and List
App.vue
<template>
<div id="app">
<div id="grid"></div>
<div id="right"></div>
</div>
</template>
<script>
export default {
name: 'app',
data () {
return {
message: 'Hello Vue!'
}
}
}
</script>
Grid.vue
<template>
<div id="left"></div>
</template>
<script>
export default {
name: 'grid',
data: function () {
return {
grid: 'some-data'
}
}
}
</script>
List.vue
<template>
<div id="right"></div>
</template>
<script>
export default {
name: 'list',
data: function () {
return {
text: 'some-text'
}
}
}
</script>
Main.js
import Vue from 'vue'
import App from './vue/App.vue'
import Grid from './vue/Grid.vue'
import PatternList from './vue/PatternList.vue'
new Vue({
el: '#app',
render: h => h(App)
});
new Vue({
el: '#grid',
render: h => h(Grid)
});
new Vue({
el: '#right',
render: h => h(PatternList)
});
它有效,但我希望这不是创建嵌套组件的正确方法。
It works but I hope this isn't the right way to create nested components.
任何人都可以表明应该这样做吗?谢谢
Can anyone show the way it should be done? Thanks
推荐答案
您可以使用 Vue.component
方法:
You can register components using the Vue.component
method:
import Vue from 'vue'
import App from './vue/App.vue'
import Grid from './vue/Grid.vue'
import PatternList from './vue/PatternList.vue'
Vue.component('grid', Grid);
Vue.component('pattern-list', PatternList);
new Vue({
el: '#app',
render: h => h(App)
});
然后将它们添加到 App
模板直接使用他们的标签名称:
And then add them to the App
template directly using their tag name:
<template>
<div id="app">
<grid></grid>
<pattern-list></pattern-list>
</div>
</template>
这会全局注册组件,这意味着任何Vue实例都可以将这些组件添加到其模板中而无需任何额外的建立。
This registers the components globally, meaning that any Vue instance can add those components to their templates without any additional setup.
您还可以将组件注册到Vue实例,如下所示:
You can also register components to a Vue instance, like so:
new Vue({
el: '#app',
render: h => h(App),
components: {
'grid': Grid,
'pattern-list': PatternList
}
});
或单个脚本
标签内-file组件:
Or within the script
tag of a single-file component:
<script>
import Grid from './vue/Grid.vue'
export default {
name: 'app',
components: {
'grid': Grid,
'pattern-list': PatternList
}
});
</script>
这会将组件注册到该Vue实例,这意味着这些注册的组件只能使用在该Vue实例的模板中。除非这些组件也注册到子Vue实例,否则子组件将无权访问这些已注册的组件。
This registers the components just to that Vue instance, meaning that those registered components will only be available to use within the template for that Vue instance. A child component would not have access to those registered components unless those components are also registered to the child Vue instance.
这篇关于Vue.js加载单文件组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!