search
HomeWeb Front-endJS TutorialHow to register a component using vue

How to register a component using vue

May 23, 2018 pm 02:56 PM
useregistercomponents

This time I will show you how to use vue to register components. What are the precautions for using vue to register components? . 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中文网其它相关文章!

    推荐阅读:

    What are the ways to use js (with code)

    How to dynamically introduce JS files

The above is the detailed content of How to register a component using vue. 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
Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools