【问题标题】:Is the way I'm writing my Vue components correct?我编写 Vue 组件的方式是否正确?
【发布时间】:2017-08-22 21:08:07
【问题描述】:

这是我目前编写 Vue 组件的方式。例如

    <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'
    })

【问题讨论】:

    标签: vue.js vuejs2


    【解决方案1】:

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

    简短的解释是&lt;template&gt;... 语法用于单文件组件(例如my-component.vue),而vue.component... 语法与new Vue({... 声明一起使用。

    来自指南的完整引用:

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

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

    • 字符串模板缺少语法高亮并且需要丑陋的斜杠 对于多行 HTML

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

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

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

    【讨论】:

    • 我会选择使您的开发最简单并易于理解应用程序结构的任何方法。
    猜你喜欢
    • 2011-06-18
    • 2018-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-07
    • 2017-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多