The style guide on the Vue official website is classified according to priority (in order: necessary, strongly recommended, recommended, and used with caution), and the code intervals are large and difficult to query. This article is classified according to type and reduces some examples or explanations. It is a streamlined version of the Vue style guide. This article mainly introduces the relevant information of the Vue streamlined style guide, including component names, instructions and features. Friends in need can refer to it. Hope it helps everyone.
Component name
[Component name is multiple words] (required)
The component name 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 Named 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 that each page can only be 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
[The component name should be described in a high-level (usually general) ) 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 should always be PascalCase in single-file components and string templates - but always kebab-case in DOM templates ] (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> <mycomponent></mycomponent> <!-- 在 DOM 模板中 --> <mycomponent></mycomponent> //good <!-- 在单文件组件和字符串模板中 --> <mycomponent></mycomponent> <!-- 在 DOM 模板中 --> <my-component></my-component>
Component related
[Single file component, string Components with no content in templates and JSX should be self-closing - but don’t do this in DOM templates] (strongly recommended)
Self-closing components mean that they not only have no content, but also deliberately have 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 to single-file components. It is not necessary to use the scoped attribute. Scoping can also be set through CSS Modules, or using other libraries or conventions
//bad <!-- 在单文件组件、字符串模板和 JSX 中 --> <mycomponent></mycomponent> <!-- 在 DOM 模板中 --> <my-component></my-component> //good <!-- 在单文件组件、字符串模板和 JSX 中 --> <mycomponent></mycomponent> <!-- 在 DOM 模板中 --> <my-component></my-component>
[Single-file components should always keep the order of <script>, <template> and <style> tags consistent 】(Recommended)</script>
//bad <template><button>X</button></template> <style> .btn-close {background-color: red;} </style> //good <template><button>X</button></template> <style> .btn-close {background-color: red;} </style> //good <template><button>X</button></template> <style> .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)
el
2. Global awareness (requires knowledge outside the component)
name
parent
3. Component type (change the type of the component)
functional
4. Template modifier (change the compilation method of the template)
delimiters
5. Template dependencies (resources used in the template)
components
filters
6. Combination (merging attributes into options)
extends
mixins
7. Interface (component interface)
inheritAttrs
modelprops/propsData
8. Local Status (local responsive properties)
data
computed
9, event (callback triggered by responsive events)
watch
Life cycle hooks (in the order they are called)
10. Non-responsive properties (instance properties that do not rely on the responsive system)
methods
11. Rendering (declarative description of component output)
template/render
renderError
prop
[Prop The definition should be as detailed as possible] (necessary)
Detailed prop definitions have two benefits: 1. They describe the API of the component, so it is easy to understand the usage of the component; 2. In the development environment, if Provide a malformed prop to a component, and Vue will alert you to help you catch potential sources of errors
//bad Vue.component('TodoList', {}) Vue.component('TodoItem', {}) //good components/ |- TodoList.vue |- TodoItem.vue
[When declaring props, their naming should always use camelCase, and in templates and JSX Use kebab-case] (strongly recommended)
//bad props: ['status'] //good props: { status: String } //better props: { status: { type: String, required: true } }
Commands and features
[Always use key with v-for] (necessary)
//bad props: {'greeting-text': String} <welcomemessage></welcomemessage> //good props: {greetingText: String} <welcomemessage></welcomemessage>
[Don’t use v- if and v-for are used on the same element at the same time] (necessary)
//bad
[Elements with multiple attributes should be written in multiple lines, one line for each attribute] (strongly recommended)
//bad
[Default order of element properties] (recommended)
1. Definition (provide options for components)
is
2. List rendering (create multiple changes) The same element)
v-for
3. Conditional rendering (whether the element is rendered/displayed)
v-if
v-else-ifv-else
v-show
v-cloak
4. Rendering method (change the rendering method of elements)
v-pre
v-once
5. Global awareness (requires knowledge beyond components)
id
6. Unique characteristics (characteristics that require unique values) )
ref
keyslot
7. Two-way binding (combine binding and events)
v-model
8. Other features (all common bound or unbound features)
9、事件 (组件事件监听器)
v-on
10、内容 (复写元素的内容)
v-html
v-text
属性
【私有属性名】(必要)
在插件、混入等扩展中始终为自定义的私有属性使用 $_ 前缀,并附带一个命名空间以回避和其它作者的冲突 (比如 $_yourPluginName_ )
//bad methods: {update: function () { }} //bad methods: {_update: function () { } } //bad methods: {$update: function () { }} //bad methods: {$_update: function () { }} //good methods: { $_myGreatMixin_update: function () { }}
【组件的data必须是一个函数】(必要)
当在组件中使用 data 属性的时候 (除了 new Vue 外的任何地方),它的值必须是返回一个对象的函数
//bad Vue.component('some-comp', { data: { foo: 'bar' } }) //good Vue.component('some-comp', { data: function () { return { foo: 'bar' } } })
【组件模板应该只包含简单的表达式,复杂的表达式则应该重构为计算属性或方法】(强烈推荐)
//bad {{ fullName.split(' ').map(function (word) { return word[0].toUpperCase() + word.slice(1) }).join(' ') }} //good computed: { normalizedFullName: function () { return this.fullName.split(' ').map(function (word) { return word[0].toUpperCase() + word.slice(1) }).join(' ') } }
【应该把复杂计算属性分割为尽可能多的更简单的属性】(强烈推荐)
//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> button { background-color: red; } </style> //good <style> .btn-close { background-color: red; } </style>
2、应该优先通过 prop 和事件进行父子组件之间的通信,而不是 this.$parent 或改变 prop
3、应该优先通过 Vuex 管理全局状态,而不是通过 this.$root 或一个全局事件总线
4、如果一组 v-if + v-else 的元素类型相同,最好使用 key (比如两个
元素)
//bad <p> 错误:{{ error }} </p> <p> {{ results }} </p> //good <p> 错误:{{ error }} </p> <p> {{ results }} </p>
相关推荐:
The above is the detailed content of Vue streamlined style code sharing. For more information, please follow other related articles on the PHP Chinese website!

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.

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 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 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 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.

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.

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.

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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.