我编写Vue组件的方式是否正确?

时间:2017-08-22 21:08:08

标签: vue.js vuejs2

这就是我目前正在编写Vue组件的方式。 E.g。

    <template>
     <NavBar></NavBar>
     <div class="Footer">
      <div class="left">
       <p>I'm a cool footer on the Left!</p>
      </div>
      <div class="middle">
      </div>
      <div class="right">
       <p>I'm a cool footer on the Right!</p>
      </div>
     </div>
    </template>

   <script>
    import NavBar from './NavBar.vue';
    export default {
     name: 'Footer',
     components: {
       NavBar
     }
     data () {
      return {
      }
     },
     methods: {
     } 
    }

我的问题是我应该像这样编写我的组件吗?如果是这样,有什么区别?

    Vue.component('my-component', {
     template: '<div>A custom component!</div>'
    })

    new Vue({
     el: '#example'
    })

1 个答案:

答案 0 :(得分:1)

官方指南解释了这里的不同之处:https://vuejs.org/v2/guide/single-file-components.html

简短说明是<template>...语法用于单文件组件(例如my-component.vue),而vue.component...语法用于new Vue({...声明。< / p>

指南全文引用:

在许多Vue项目中,将使用Vue.component定义全局组件,然后使用new Vue({ el: '#container' })来定位每个页面正文中的容器元素。 这对于中小型项目非常有效,其中JavaScript仅用于增强某些视图。然而,在更复杂的项目中,或者当您的前端完全由JavaScript驱动时,这些缺点变得明显:

  • 全局定义强制每个组件的唯一名称

  • 字符串模板缺少语法突出显示,需要粗斜杠 用于多行HTML

  • 没有CSS支持意味着HTML和JavaScript是模块化的 在组件中,CSS显然被忽略了

  • 没有构建步骤限制我们使用HTML和ES5 JavaScript,而不是 预处理器如Pug(以前的Jade)和Babel

所有这些都通过具有.vue扩展名的单文件组件解决,通过Webpack或Browserify等构建工具实现。