search
HomeWeb Front-endJS TutorialInstructions for using vue registration components

This time I will bring you the step-by-step instructions for using the vue registration component. What are the precautions when using the vue registration component? The following is a practical case, let’s take a look.

1. Introduction

The component system is one of the important concepts of Vue.js. It provides an abstraction that we can use Independent and reusable small components are used to build large-scale applications. Any type of application interface can be abstracted into a component tree

So what are components?

Components can extend HTML elements and encapsulate reusable HTML code. We can think of components as custom HTML elements.

2. How to register a component

The use of components of Vue.jsThere are 3 steps: Create a component structure controller, register components and use components.

The following code demonstrates these three steps

nbsp;html>

 
  <p>
   <!-- 注意: #app是Vue实例挂载的元素,应该在挂载元素范围内使用组件-->
   <my-component></my-component>
  </p>
 
 <script></script>
 <script>
  <!-- 1.创建一个组件构造器 -->
  var myComponent = Vue.extend({
   template: &#39;<p>This is my first component!&#39;
  })
  
  <!-- 2.注册组件,并指定组件的标签,组件的HTML标签为<my-component> -->
  Vue.component(&#39;my-component&#39;, myComponent)
  
  <!-- 3.通过id=app进行挂载 -->
  new Vue({
   el: &#39;#app&#39;
  });
  
 </script>

The running results are as follows:

1. Global registration and local registration

When calling Vue.component() to register a component, the component's registration is global, which means that the component can be used in any Vue example.
If you do not need global registration, or if you want the component to be used in other components, you can use the components attribute of the options object to implement local registration.

My own understanding is that components represent global components, and components represent local components.

The above example can be changed to local registration:

nbsp;html>

 
  <p>
   <!-- 3. my-component只能在#app下使用-->
   <my-component></my-component>
  </p>
 
 <script></script>
 <script>
  // 1.创建一个组件构造器
  var myComponent = Vue.extend({
   template: &#39;<p>This is my first component!&#39;
  })
  
  new Vue({
   el: &#39;#app&#39;,
   components: {
   // 2. 将myComponent组件注册到Vue实例下
    &#39;my-component&#39; : myComponent
   }
  });
 </script>

Since my-component The component is registered under the Vue instance corresponding to the #app element, so it cannot be used under other Vue instances.

<p>
 <!-- 不能使用my-component组件,因为my-component是一个局部组件,它属于#app-->
 <my-component></my-component>
</p>
<script>
 new Vue({
  el: &#39;#app2&#39;
 });
</script>

2. Component registration syntax sugar

The above component registration method is a bit cumbersome. In order to simplify this process, Vue.js provides registration Syntax sugar

// 全局注册,my-component1是标签名称
Vue.component('my-component1',{
 template: '<p>This is the first component!</p>'
})
var vm1 = new Vue({
 el: '#app1'
})

The first parameter of Vue.component() is the label name, and the second parameter is an option object. Use the template attribute of the option object to define the componenttemplate.
Using this method, Vue will automatically call Vue.extend() behind the scenes.

Components implement local registration

var vm2 = new Vue({
 el: '#app2',
 components: {
  // 局部注册,my-component2是标签名称
  'my-component2': {
   template: '<p>This is the second component!</p>'
  },
  // 局部注册,my-component3是标签名称
  'my-component3': {
   template: '<p>This is the third component!</p>'
  }
 }
}

3. Parent component and child component

We can define and use other components in the component, which constitutes The relationship between parent and child components.

nbsp;html>

 
  <p>
   <parent-component>
   </parent-component>
  </p>
 
 <script></script>
 <script>
  
  var Child = Vue.extend({
   template: &#39;<p>This is a child component!&#39;
  })
  
  var Parent = Vue.extend({
   // 在Parent组件内使用<child-component>标签
   template :&#39;<p>This is a Parent component<child-component>&#39;,
   components: {
    // 局部注册Child组件,该组件只能在Parent组件内使用
    &#39;child-component&#39;: Child
   }
  })
  
  // 全局注册Parent组件
  Vue.component(&#39;parent-component&#39;, Parent)
  
  new Vue({
   el: &#39;#app&#39;
  })
  
 </script>

The running result of this code is as follows

4. Use script or template tag

Although the syntax Sugar simplifies component registration, but splicing HTML elements in the template option is more troublesome, which also leads to high coupling between HTML and JavaScript.
Fortunately, Vue.js provides two ways to separate HTML templates defined in JavaScript.

nbsp;html>


 <meta>
 <title>vue组件</title>
 <script></script>


 <p>
  <my-com></my-com>
  <my-com1></my-com1>
 </p>
 <template>
  <p>这是template标签构建的组件</p>
 </template>
 <script>
  <p>这是script标签构建的组件
 </script>
 <script></script>
 <script>
  Vue.component(&#39;my-com1&#39;, {
   template: &#39;#myCom1&#39;
  });
  var app1 = new Vue({
   el: &#39;#app1&#39;,
   components: {
    &#39;my-com&#39;: {
     template: &#39;#myCom&#39;
    }
   }
  });
 </script>

Running results:

Note: When using the <script> tag, type is specified as text/x-template, which is intended to tell the browser this It is not a js script. The browser will ignore the content defined in the <script> tag when parsing the HTML document. </script>

      在理解了组件的创建和注册过程后,我建议使用<script>或<template>标签来定义组件的HTML模板。<br/>这使得HTML代码和JavaScript代码是分离的,便于阅读和维护。</script>

 五、模板的注意事项

     1. 以子标签的形式在父组件中使用

<p>
 <parent-component>
  <child-component></child-component>
 </parent-component>
</p>

 上面是错误的。为什么这种方式无效呢?因为当子组件注册到父组件时,Vue.js会编译好父组件的模板,模板的内容已经决定了父组件将要渲染的HTML。

<parent-component>…</parent-component>相当于运行时,它的一些子标签只会被当作普通的HTML来执行,component>不是标准的HTML标签,会被浏览器直接忽视掉

     2.组件的模板只能有一个根元素。下面的情况是不允许的。

template: `

这是一个局部的自定义组件,只能在当前Vue实例中使用


            `

     3.组件中的data必须是函数

       注册组件时传入的配置和创建Vue实例差不多,但也有不同,其中一个就是data属性必须是一个函数。

这是因为如果像Vue实例那样,传入一个对象,由于JS中对象类型的变量实际上保存的是对象的引用,所以当存在多个这样的组件时,会共享数据,导致一个组件中数据的改变会引起其他组件数据的改变。

而使用一个返回对象的函数,每次使用组件都会创建一个新的对象,这样就不会出现共享数据的问题来了。

     4.关于DOM模板的解析

       当使用 DOM 作为模版时 (例如,将 el 选项挂载到一个已存在的元素上), 你会受到 HTML 的一些限制,因为 Vue 只有在浏览器解析和标准化 HTML 后才能获取模板内容。尤其像这些元素

    ,,
     ...

            自定义组件 被认为是无效的内容,因此在渲染的时候会导致错误。这时应使用特殊的 is 属性:

    
    
     

           也就是说,标准HTML中,一些元素中只能放置特定的子元素,另一些元素只能存在于特定的父元素中。比如table中不能放置p,tr的父元素不能p等。所以,当使用自定义标签时,标签名还是那些标签的名字,但是可以在标签的is属性中填写自定义组件的名字。

    三、动态组件

        有的时候,在不同组件之间进行动态切换是非常有用的,比如在一个多标签的界面里

        简单点说:就是几个组件放在一个挂载点下,然后根据父组件的某个变量来决定显示哪个,或者都不显示。

        要点:在挂载点使用component标签,然后使用v-bind:is=”组件名”,会自动去找匹配的组件名,如果没有,则不显示

    动态组件,先看案例效果:

    代码演示:css代码就不复制了,上面案例效果里有。

    <script></script>
    <p>
     <button>{{ tab }}</button>
     <component></component>
    </p>

         这里v-bind:key其实可有可无,具体key介绍可以看官网。

         这里v-bind:class和v-on:click都是用来为了改变样式用的。

        关键是component组件标签。

    <script>
     //显示定义了三个组件
     Vue.component(&#39;tab-科长&#39;, {
      template: &#39;<p>一共有100个科长&#39;
     })
     Vue.component(&#39;tab-处长&#39;, {
      template: &#39;<p>一种有50个处长&#39;
     })
     Vue.component(&#39;tab-局长&#39;, {
      template: &#39;<p>一共有10个局长&#39;
     })
     new Vue({
      el: &#39;#dynamic-component-demo&#39;,
      data: {
       currentTab: &#39;局长&#39;,
       tabs: [&#39;科长&#39;, &#39;处长&#39;, &#39;局长&#39;]
      },
     //计算属性,根据currentTab的改变来判断选择哪个组件
      computed: {
       currentTabComponent: function() {
        return &#39;tab-&#39; + this.currentTab
       }
      }
     })
    </script>

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

    推荐阅读:

    Summary of cross-domain methods that js supports post requests

    Detailed explanation of Vue.js calculation and listener attribute usage

The above is the detailed content of Instructions for using vue registration 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 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.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor