我刚看完Vue的指南.js的网站,我对组件的模板感觉不好.我觉得奇怪的是,它们是用字符串指定的;当然,这可能适用于非常短的模板,但一旦你使用了多行模板,你需要开始转义新行,开始使用javascript字符串的html感觉就像wrong.更不用说语法高亮显示或任何其他优秀的IDE功能对于JS字符串中的HTML都是无用的.

文档中详细说明的两个备选方案是使用inline templatesX-templates,但不鼓励使用这两个选项.

唯一的替代方案似乎是Single File Components,这似乎是一个不错的 Select ,但在Advanced部分和文档中,据说对于中小型应用程序来说,简单地使用Vue.component就足够了.此外,单文件组件看起来更难集成到项目中,需要进入项目的构建系统(文档中提到了Webpack和Browserify).

所以我很困惑.我是否需要接受我的组件代码会像这个例子一样凌乱,直接从文档中提取?

Vue.component('currency-input', {
  template: '\
    <span>\
      $\
      <input\
        ref="input"\
        v-bind:value="value"\
        v-on:input="updateValue($event.target.value)"\
      >\
    </span>\
  ',
......

推荐答案

考虑到您正在启动一个新项目,您可以使用vue-hackernews-2.0作为样板,在这里您可以看到许多组件已经使用webpack集成为dev和prod env编写.该团队也是由vue official docs开发的.

JS的每一个组件都有一个清晰的分隔,每个组件看起来都像是different files:

<template>
  <li v-if="comment" class="comment">
    <div class="by">
      <router-link :to="'/user/' + comment.by">{{ comment.by }}</router-link>
      {{ comment.time | timeAgo }} ago
    </div>
    <div class="text" v-html="comment.text"></div>
    <div class="toggle" :class="{ open }" v-if="comment.kids && comment.kids.length">
      <a @click="open = !open">{{
        open
            ? '[-]'
            : '[+] ' + pluralize(comment.kids.length) + ' collapsed'
      }}</a>
    </div>
    <ul class="comment-children" v-show="open">
      <comment v-for="id in comment.kids" :id="id"></comment>
    </ul>
  </li>
</template>

<script>
export default {
  name: 'comment',
  props: ['id'],
  data () {
    return {
      open: true
    }
  },
  computed: {
    comment () {
      return this.$store.state.items[this.id]
    }
  },
  methods: {
    pluralize: n => n + (n === 1 ? ' reply' : ' replies')
  }
}
</script>

<style lang="stylus">
.comment-children
  .comment-children
    margin-left 1.5em
.comment
  border-top 1px solid #eee
  position relative
  .by, .text, .toggle
    font-size .9em
    margin 1em 0
  .by
    color #999
    a
      color #999
      text-decoration underline
  .text
    overflow-wrap break-word
    a:hover
      color #ff6600
    pre
      white-space pre-wrap
  .toggle
    background-color #fffbf2
    padding .3em .5em
    border-radius 4px
    a
      color #999
      cursor pointer
    &.open
      padding 0
      background-color transparent
      margin-bottom -0.5em
</style>

这使用webpack进行构建,并添加了working config,我自己也在生产中使用,没有任何问题.

Vue.js相关问答推荐

为什么发送 POST API 请求时主体对象没有react ?

元素不会对react 性props 的更改做出react

Vuetify/Nuxt 生产环境组件在开发环境中无法正常工作

两个div元素之间的vue2过渡

如何在 Vue.js 中获取完整的当前日期和时间,而无需编写大量 JavaScript 行

为什么Vue.js 使用单字标签

如何在某些异步数据(在 Vuex 存储中)加载之前防止任何路由?

将 props 传递给 Vue 组件中的元素属性

我可以在 Vue 实例方法中传播的 mapMutations 中使用this吗?

如何在 Vue 中动态创建组件上获取更新的 $refs?

如何在 Vue.js 应用程序中正确下载 Excel 文件?

Vuex 存储数据总是驻留在内存中?

构建 Vue.js 应用程序时 JavaScript 堆内存不足

如何在 NuxtJS 中设置全局 $axios 标头

vuex - 即使不推荐,是否可以直接更改状态?

如何从浏览器的源中删除 webpack://

Axios 请求拦截器在我的 vue 应用程序中不起作用

在 Vue 单元测试中单击按钮时触发表单提交

将 Vue props与默认值合并

v-bind:class 的 Vue.js 计算(computed)属性