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
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
<!-- 在单文件组件、字符串模板和 JSX 中 -->
<MyComponent></MyComponent>
<!-- 在 DOM 模板中 -->
<my-component/>
//good
<!-- 在单文件组件、字符串模板和 JSX 中 -->
<MyComponent/>
<!-- 在 DOM 模板中 -->
<my-component></my-component></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('TodoList', {}) Vue.component('TodoItem', {}) //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: ['status'] //good props: { status: String } //better props: { status: { type: String, required: true } }
Commands and features
[Always use key with v-for] (required)
//bad props: {'greeting-text': 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('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 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>
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
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!

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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