Home >Web Front-end >JS Tutorial >How 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
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 3f1c4e4b6b16bbbd69b2ee476dc4f83a, d477f9ce7bf77f53fbcf36bec1b69b7a and c9ccee2e6ea535a969eb3f532ad9fe89 tags consistent 】(Recommended)
//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="https://vuejs.org/images/logo.png"> //good <img src="https://vuejs.org/images/logo.png" >
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
(比如两个 e388a4556c0f65e1904146cc1a846bee
元素)
//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!