Vue.js加载单文件组件

Dmi*_*try 18 javascript vue-component vuejs2

我是Vue.js的新手,想要使用单文件组件,但我不了解工作流程.

例如,我有三个组成部分:App,GridList

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>
Run Code Online (Sandbox Code Playgroud)

Grid.vue

<template>
    <div id="left"></div>
</template>

<script>
    export default {
        name: 'grid',
        data: function () {
            return {
                grid: 'some-data'
            }
        }
    }
</script>
Run Code Online (Sandbox Code Playgroud)

List.vue

<template>
    <div id="right"></div>
</template>

<script>
    export default {
    name: 'list',
    data: function () {
        return {
            text: 'some-text'
        }
    }
}
</script>
Run Code Online (Sandbox Code Playgroud)

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)
});
Run Code Online (Sandbox Code Playgroud)

它有效,但我希望这不是创建嵌套组件的正确方法.

任何人都可以展示它应该做的方式吗?谢谢

tha*_*ksd 55

您可以使用以下Vue.component方法注册组件:

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)
});
Run Code Online (Sandbox Code Playgroud)

然后App使用其标记名称将它们直接添加到模板中:

<template>
  <div id="app">
    <grid></grid>
    <pattern-list></pattern-list>
  </div>
</template>
Run Code Online (Sandbox Code Playgroud)

这会全局注册组件,这意味着任何Vue实例都可以将这些组件添加到其模板中,而无需任何其他设置.


您还可以将组件注册到Vue实例,如下所示:

new Vue({
  el: '#app',
  render: h => h(App),
  components: {
    'grid': Grid,
    'pattern-list': PatternList
  }
});
Run Code Online (Sandbox Code Playgroud)

或者在script单个文件组件的标记内:

<script>
import Grid from './vue/Grid.vue'

export default {
  name: 'app',
  components: {
    'grid': Grid,
    'pattern-list': PatternList
  }
});
</script>
Run Code Online (Sandbox Code Playgroud)

这会将组件注册到该Vue实例,这意味着这些注册的组件只能在该Vue实例的模板中使用.除非这些组件也注册到子Vue实例,否则子组件将无法访问这些已注册的组件.

  • 非常感谢!这就是我在寻找的东西. (6认同)
  • 很好的回应,这是一个很好的例子,说明了堆栈溢出的答案有多好。 (2认同)