如何在 vue.js 文件中注释代码?

我需要在 vue.js 文件中插入一条注释以便将来引用,但是我在文档中没有找到如何做到这一点。

我试过 ///**/{{-- --}}{# #},但似乎都不管用。

我用的是 Laravel 的刀,这是 sample_file.vue:

<template>
<div class="media">


<like-button :post="post" v-if="post.likedByCurrentUser === false && "></like-button>  {{--I want to comment this but I get an error from the gulp watch: post.canBeLikedByCurrentUser === true--}}


<div class="media-left">
<a href="#">
<img class="media-object" v-bind:src="post.user.avatar" v-bind:title="post.user.name + ' image from Gravatar'">
</a>
</div>
<div class="media-body">
<strong>{{ post.user.name }}</strong>
<p>{{post.body}}</p>
<p>{{post.likeCount}} {{ pluralize('like', post.likeCount) }}</p>
</div>
</div>
</template>

是否有人知道如何插入注释和/或如何注释代码段?

172142 次浏览

我在 Vue.js 中是菜鸟,但是 //应该可以工作,因为代码是 javascript。 我在文件里找到了这个 例子。如果你看一下 javascript 的前两行,你会看到 //的注释。

例子在 javascript 链接文件:

// Full spec-compliant TodoMVC with localStorage persistence
// and hash-based routing in ~120 effective lines of JavaScript.


...

在您的情况下,您可能希望在 <template>标记中使用标准的 HTML 注释。它们也会从输出中被剥离出来,这很好。

<!-- Comment -->

正如 Bill Criswell 所说,我们可以使用 HTML 注释语法。

<!-- Comment -->

但是,它也可以在模板标签之外工作, 评论

<!-- Testing comments, this will work too. -->


<template>
<!-- This will work too -->


<div>
<!-- Html Comments -->
Hello There!
</div>
</template>


<style><style>


<!-- Commenting here -->


<script>
// Commenting only 1 line


/**
* Commenting multiple lines
* Commenting multiple lines
*/
</script>

我注意到当你在一个标签里面的时候你不能评论:

<!-- make sure it is outside a tag -->


<autocomplete
<!-- you can't place the comment out in here -->
>
</autocomplete>

下面的技巧与其说是关于 评论代码本身(如在编写文档时) ,不如说是关于允许您在开发期间暂时跳过代码块。

当注释需要开始和结束标记时,解析器匹配它们的方式可能不方便。例如

<!-- I want to comment this <!-- this --> and that -->

将输出 and that -->。类似的 /* this will be commented /* and so will this */ but not this */

我的解决方案是使用 v-if="false"来指定我想(暂时)跳过的块。

<template>
<div>
Hello
<div v-if="false">
Vue will not process whatever's in here.
</div>
World!
</div>
</template>

请注意,这不应该用于替换记录代码的正确注释。这只是一种方便的方法,可以对开发过程中想要跳过的块进行更多的控制。

我刚刚测试了一下:

<template>
\{\{ /* this is a comment */ }}
<h1>Hello world</h1>
</template>

Vue Styleguide 包含最佳实践,并显示了如何注释组件的示例。 Https://vue-styleguidist.github.io/docs/documenting.html#code-comments

但总的来说..。

模板或 HTML 部分使用 HTML 注释

<!-- Comment -->

剧本部分使用 Javascript 注释

// Comment
/* Comment */

风格部分使用 CSS 注释

/* comment */

如果它对您的项目有用,您可以将纯文本置于模板之上,而不进行任何修饰。在呈现组件时,它将被完全忽略。

This is some documentation about this component
- some
- info
<template></template>
<script></script>
<style></style>

在 Vue file/. Vue 中使用

/*-- comment in Vue file */

根据需要的特定行为,可以在模板部分添加注释:

  <template>
<!-- comment incorporated in the rendered output. -->
<aside v-if="false">Some comment that won’t be in the output result.</aside>
</template>

当然,对于后者,不需要使用 aside标记,任何虚假的计算值都可以达到这个目的。所以 <i v-if="0">Some comment</i>也能正常工作。

诚然,这有点复杂,但 Vue 似乎没有提供更直接的选择。