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 in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

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.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.