search
HomeWeb Front-endJS TutorialHow to implement a streamlined style in Vue (detailed tutorial)

This article explains the relevant knowledge points of the Vue streamlined style and shares the example code. Interested friends can refer to it.

The previous words

The style guide on the Vue official website is classified according to priority (in order of necessary, strongly recommended, recommended, and used with caution), and the code intervals are large and difficult to query. This article is classified by type and reduces some examples or explanations. It is a streamlined version of the Vue style guide

Component name

[Component name is multiple words] (required)

Component names should always be multiple words, except for the root component App. Doing so avoids conflicts with existing and future HTML elements, since all HTML element names are single-word names. , or always connected with a horizontal line (kebab-case)] (strongly recommended)

//bad
Vue.component('todo', {})
//good
Vue.component('todo-item', {})

[The basic component name must start with a specific prefix] (strongly recommended)

Apply specific styles and conventions Base components (that is, presentational, non-logical, or stateless components) should all start with a specific prefix, such as Base, App, or V

//bad
mycomponent.vue
//good
MyComponent.vue
//good
my-component.vue

[Components that should only have a single active instance should Name it with the prefix

The

to show its uniqueness] (strongly recommended) This does not mean that the component can only be used on a single page, but

each page

Only used once, these components will never accept any prop

//bad
components/
|- MyButton.vue
|- VueTable.vue
|- Icon.vue
//good
components/
|- BaseButton.vue
|- BaseTable.vue
|- BaseIcon.vue
[Subcomponents that are tightly coupled with the parent component should be named with the parent component name as a prefix] (strongly recommended)

//bad
components/
|- Heading.vue
|- MySidebar.vue
//good
components/
|- TheHeading.vue
|- TheSidebar.vue

[Component name It should start with a high-level (usually general description) word and end with a descriptive modifier] (strongly recommended)

//bad
components/
|- TodoList.vue
|- TodoItem.vue
|- TodoButton.vue
//good
components/
|- SearchSidebar.vue
|- SearchSidebarNavigation.vue

[The component name in single-file components and string templates should always be PascalCase ——But always kebab-case in DOM template] (strongly recommended)

//bad
components/
|- ClearSearchButton.vue
|- ExcludeFromSearchInput.vue
|- LaunchOnStartupCheckbox.vue
|- RunSearchButton.vue
|- SearchInput.vue
|- TermsCheckbox.vue
//good
components/
|- SearchButtonClear.vue
|- SearchButtonRun.vue
|- SearchInputQuery.vue
|- SearchInputExcludeGlob.vue
|- SettingsCheckboxTerms.vue
|- SettingsCheckboxLaunchOnStartup.vue

[Component names should tend to be complete words rather than abbreviations] (strongly recommended)

//bad
<!-- 在单文件组件和字符串模板中 -->
<mycomponent/>
<myComponent/>
<!-- 在 DOM 模板中 -->
<MyComponent></MyComponent>
//good
<!-- 在单文件组件和字符串模板中 -->
<MyComponent/>
<!-- 在 DOM 模板中 -->
<my-component></my-component>

Component related

[Single file components, string templates and components without content in JSX should be self-closing - but don’t do this in DOM templates] (strongly recommended)

Self-closing components mean that they are not only No content, and deliberately no content

//bad
components/
|- SdSettings.vue
|- UProfOpts.vue
//good
components/
|- StudentDashboardSettings.vue
|- UserProfileOptions.vue

[Set scope for component styles] (required)

This rule is only relevant for single-file components.

It is not necessary to

use the scoped feature. Scoping can also be set through CSS Modules, or using other libraries or conventions<pre class='brush:php;toolbar:false;'>//bad &lt;!-- 在单文件组件、字符串模板和 JSX 中 --&gt; &lt;MyComponent&gt;&lt;/MyComponent&gt; &lt;!-- 在 DOM 模板中 --&gt; &lt;my-component/&gt; //good &lt;!-- 在单文件组件、字符串模板和 JSX 中 --&gt; &lt;MyComponent/&gt; &lt;!-- 在 DOM 模板中 --&gt; &lt;my-component&gt;&lt;/my-component&gt;</pre>[Single-file components should always keep the order of <script>, <template> and <style> tags consistent 】(Recommended)</script>

//bad
<template><button class="btn btn-close">X</button></template>
<style>
.btn-close {background-color: red;}
</style>
//good
<template><button class="btn btn-close">X</button></template>
<style scoped>
.btn-close {background-color: red;}
</style>
//good
<template><button :class="[$style.button, $style.buttonClose]">X</button></template>
<style module>
.btn-close {background-color: red;}
</style>

[Only one component in one file](Strongly recommended)

//good
<!-- ComponentA.vue -->
<script>/* ... */</script>
<template>...</template>
<style>/* ... */</style>

<!-- ComponentB.vue -->
<script>/* ... */</script>
<template>...</template>
<style>/* ... */</style>

[Default order of component options](Recommended)

1. Side effects (trigger Influence outside the component)

//bad
Vue.component(&#39;TodoList&#39;, {})
Vue.component(&#39;TodoItem&#39;, {})
//good
components/
|- TodoList.vue
|- TodoItem.vue

2. Global awareness (requires knowledge outside the component)

el

3. Component type (change the type of component)

name
parent

4. Template Modifier (change the compilation method of the template)

functional

5. Template dependency (resources used in the template)

delimiters
comments

6. Combination (merge attributes into options)

components
directives
filters

7. Interface (interface of component)

extends
mixins

8. Local state (local responsive attribute)

inheritAttrs
model
props/propsData

9. Event (callback triggered by responsive event)

data
computed

10. Non-responsive properties (instance properties that do not rely on the responsive system)

watch
生命周期钩子 (按照它们被调用的顺序)

11. Rendering (declarative description of component output)

methods

prop

[Prop definitions should be as detailed as possible] (necessary)

Detailed prop definitions have two benefits: 1. They specify the API of the component, so it is easy to understand the usage of the component; 2. In the development environment Below, if you provide a malformed prop to a component, Vue will alert you to help you catch potential sources of errors

template/render
renderError

[When declaring props, their naming should always use camelCase, and in templates and JSX kebab-case should always be used] (strongly recommended)

//bad
props: [&#39;status&#39;]
//good
props: {
 status: String
}
//better
props: {
 status: {
  type: String,
  required: true
 }
}

Commands and features

[Always use key with v-for] (required)

//bad
props: {&#39;greeting-text&#39;: String}
<WelcomeMessage greetingText="hi"/>
//good
props: {greetingText: String}
<WelcomeMessage greeting-text="hi"/>

[Don’t Use v-if and v-for on the same element at the same time] (necessary)

//bad
 <li v-for="todo in todos">
//good
 <li v-for="todo in todos":key="todo.id">

[Elements with multiple attributes should be written in multiple lines, one line for each attribute] (strongly recommended)

//bad
<li v-for="user in users" v-if="user.isActive" :key="user.id" > {{ user.name }} <li>
//good
<li v-for="user in users" v-if="shouldShowUsers" :key="user.id" > {{ user.name }} <li>

[Default order of element properties] (recommended)

1. Definition (providing component options)

//bad
<img  src="/static/imghwm/default1.png"  data-src="https://vuejs.org/images/logo.png"  class="lazy"   alt="How to implement a streamlined style in Vue (detailed tutorial)" >
//good
<img src="/static/imghwm/default1.png"  data-src="https://vuejs.org/images/logo.png"  class="lazy" 
 
 
>

2. List rendering (create multiple variations of the same element)

is

3. Conditional rendering (whether the element is rendered/displayed)

v-for

4. Rendering method (change the rendering method of the element)

v-if
v-else-if
v-else
v-show
v-cloak

5. Global perception (needs to transcend components Knowledge)

v-pre
v-once

6. Unique characteristics (characteristics that require unique values)

id

7. Two-way binding (combining bindings with events)

ref
key
slot

8 , Other characteristics (all ordinary bound or unbound characteristics)

9. Events (component event listeners)

v-model

10. Content (copy the content of the element)

v-on

Attribute

[Private attribute name](required)

Always use $_ prefix for customized private attributes in plug-ins, mixins and other extensions, and attach a namespace to Avoid conflicts with other authors (such as $_yourPluginName_)

v-html
v-text

[The data of the component must be a function] (required)

当在组件中使用 data 属性的时候 (除了 new Vue 外的任何地方),它的值必须是返回一个对象的函数

//bad
Vue.component(&#39;some-comp&#39;, {
 data: {
  foo: &#39;bar&#39;
 }
})
//good
Vue.component(&#39;some-comp&#39;, {
 data: function () {
  return {
   foo: &#39;bar&#39;
  }
 }
})

【组件模板应该只包含简单的表达式,复杂的表达式则应该重构为计算属性或方法】(强烈推荐)

//bad
{{
 fullName.split(&#39; &#39;).map(function (word) {
  return word[0].toUpperCase() + word.slice(1)
 }).join(&#39; &#39;)
}}
//good
computed: {
 normalizedFullName: function () {
  return this.fullName.split(&#39; &#39;).map(function (word) {
   return word[0].toUpperCase() + word.slice(1)
  }).join(&#39; &#39;)
 }
}

【应该把复杂计算属性分割为尽可能多的更简单的属性】(强烈推荐)

//bad
computed: {
 price: function () {
  var basePrice = this.manufactureCost / (1 - this.profitMargin)
  return (
   basePrice -
   basePrice * (this.discountPercent || 0)
  )
 }
}
//good
computed: {
 basePrice: function () {
  return this.manufactureCost / (1 - this.profitMargin)
 },
 discount: function () {
  return this.basePrice * (this.discountPercent || 0)
 },
 finalPrice: function () {
  return this.basePrice - this.discount
 }
}

【当组件开始觉得密集或难以阅读时,在多个属性之间添加空行可以让其变得容易】(推荐)

//good
props: {
 value: {
  type: String,
  required: true
 },

 focused: {
  type: Boolean,
  default: false
 }
}

谨慎使用

1、元素选择器应该避免在 scoped 中出现

在 scoped 样式中,类选择器比元素选择器更好,因为大量使用元素选择器是很慢的

//bad
<style scoped>
button {
 background-color: red;
}
</style>
//good
<style scoped>
.btn-close {
 background-color: red;
}
</style>

2、应该优先通过 prop 和事件进行父子组件之间的通信,而不是 this.$parent 或改变 prop

3、应该优先通过 Vuex 管理全局状态,而不是通过 this.$root 或一个全局事件总线

4、如果一组 v-if + v-else 的元素类型相同,最好使用 key (比如两个 <p></p> 元素)

//bad
<p v-if="error">
 错误:{{ error }}
</p>
<p v-else>
 {{ results }}
</p>
//good
<p
 v-if="error"
 key="search-status"
>
 错误:{{ error }}
</p>
<p 
 v-else 
 key="search-results"
>
 {{ results }}
</p>

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

JavaScript的6种正则表达式(详细教程)

react webpack打包后的文件(详细教程)

在微信小程序中如何实现圆形进度条

The above is the detailed content of How to implement a streamlined style in Vue (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool