search
HomeWeb Front-endJS TutorialDetailed explanation of the use of vue components

Detailed explanation of the use of vue components

May 14, 2018 am 10:52 AM
usecomponentsDetailed explanation

This time I will bring you a detailed explanation of the use of vue components, and a detailed explanation of the precautions for the use of vue components. The following is a practical case, let's take a look.

Component (Component) is a simple encapsulation of data and methods. The component in the web can actually be regarded as a component of the page. It is an interface with independent logic and functions. At the same time, it can be integrated with each other according to the specified interface rules, and finally becomes a complete application. The page is composed of a It is composed of similar components, such as navigation, list, pop-up window, drop-down menu, etc. The page is just a container for such components. The components are freely combined to form a fully functional interface. When a component is not needed or you want to replace it, you can replace and delete it at any time without affecting the operation of the entire application. , The core idea of ​​front-end componentization is to split a huge and complex thing into small things with reasonable granularity.

Use to improve development efficiency, facilitate reuse, simplify debugging steps, improve the maintainability of the entire project, and facilitate collaborative development.

As a lightweight front-end framework, vue’s core is component development.

Components can extend HTML elements and encapsulate reusable code. At a high level, a component is a custom element to which Vue.js's compiler adds special functionality. In some cases, components can also appear as native HTML elements extended with the is attribute.

In vue, components are reusable Vue instances. Because components are reusable Vue instances, they receive the same options as new Vue, such as data, computed, watch, methods, and lifecyclehooks. The only exceptions are root-instance-specific options like el.

Component registration

Global registration

Create components through Vue.component:

 Vue.component('my-component-name', {
 // ... 选项 ...
 })

These Components are registered globally. That is to say, they can be used in the template of any newly created Vue root instance (new Vue) after registration. For example:

Vue.component('component-a', { /* ... */ })
Vue.component('component-b', { /* ... */ })
Vue.component('component-c', { /* ... */ })
new Vue({ el: '#app' })
<p>
 <component-a></component-a>
 <component-b></component-b>
 <component-c></component-c>
</p>

The same is true in all sub-components, which means that these three components can also use each other internally.

Local registration

Global registration is often not ideal. For example, if you use a build system like webpack, registering all components globally means that even if you no longer use a component, it will still be included in your final build result. This results in an unnecessary increase in the amount of JavaScript downloaded by users.

In these cases, you can define the component via a plain JavaScript object:

var ComponentA = { /* ... */ }
var ComponentB = { /* ... */ }
var ComponentC = { /* ... */ }

Then define the component you want to use in the components options:

new Vue({
 el: '#app'
 components: {
 'component-a': ComponentA,
 'component-b': ComponentB
 }
})

For each attribute in the components object, its attribute name is the name of the custom element, and its attribute value is the option object of this component.
Note that locally registered components are not available in their child components. For example, if you want ComponentA to be available in ComponentB, you need to write like this:

var ComponentA = { /* ... */ }
var ComponentB = {
 components: {
 'component-a': ComponentA
 },
 // ...
}

Use registered components in Babel and webpack

import ComponentA from './ComponentA.vue'
export default {
 components: {
 ComponentA
 },
 // ...
}

Note that in ES2015, Putting a variable name similar to ComponentA in the object is actually ComponentA: the abbreviation of ComponentA, that is, the variable name is also:

The name of the custom element used in the template
Contains the option of this component Variable name

Automated global registration of basic components

I don’t understand.

data must be a function

data: {
 count: 0
}

The variables in the data defined in this way are global variables. When using components, modifying the value of the variable in one component will affect the value in all components. The value of the variable. To avoid variable interference, a component's data option must be a function, so each instance can maintain an independent copy of the returned object:

data: function () {
 return {
 count: 0
 }
}

Dynamic components

It is very useful to dynamically switch between different components, such as in a multi-tab interface:

##The above content can be passed through Vue's element Add a special is attribute to achieve this:

<!-- 组件会在 `currentTabComponent` 改变时改变 -->
<component></component>

你会注意到,如果你选择了一篇文章,切换到 Archive 标签,然后再切换回 Posts,是不会继续展示你之前选择的文章的。这是因为你每次切换新标签的时候,Vue 都创建了一个新的 currentTabComponent 实例。

重新创建动态组件的行为通常是非常有用的,但是在这个案例中,我们更希望那些标签的组件实例能够被在它们第一次被创建的时候缓存下来。为了解决这个问题,我们可以用一个 元素将其动态组件包裹起来。

<!-- 失活的组件将会被缓存!-->
<keep-alive>
 <component></component>
</keep-alive>

可以在这里查看动态组件例子。https://jsfiddle.net/chrisvfritz/Lp20op9o/

dom标签内使用组件

有些 HTML 元素,诸如

    、 和
     

    这个自定义组件 会被作为无效的内容提升到外部,并导致最终渲染结果出错。幸好这个特殊的 is 特性给了我们一个变通的办法:

    
    
     

    相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

    推荐阅读:

    JS做出哈希表功能

    Vue父子组件数据传递方法总结(附代码)

The above is the detailed content of Detailed explanation of the use of vue components. 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

Video Face Swap

Video Face Swap

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

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.