Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Vue 3 Components

Vue 3 Components

Every Vue component is an independent Vue instance with its own template, data, methods, and lifecycle hooks, enabling the component to define and manage its own functionality and styles in a self-contained way.

The component is one of the most powerful features of Vue.js.

Components can extend HTML elements and encapsulate reusable code, helping you split the user interface into independent and reusable parts.

Every Vue component is an independent Vue instance with its own template, data, methods, and lifecycle hooks, enabling the component to define and manage its own functionality and styles in a self-contained way.

Features and Advantages of Vue Components

The component system lets us build large applications from independent, reusable small components; almost any type of application interface can be abstracted into a component tree:

Every Vue application is created with the createApp function, and the options passed to createApp are used to configure the root component. When we mount the application, this component is used as the starting point for rendering.

An application needs to be mounted into a DOM element.

In the following example we mount the Vue application to

, and should pass #app:

const RootComponent = { /* 选项 */ }

const app = Vue.createApp(RootComponent)

const vm = app.mount('#app')

The syntax format for registering a global component is as follows:



const app = Vue.createApp({...})



app.component('my-component-name', {

  /* ... */

})

my-component-name is the component name, **/* ... /* is the configuration options. After registration, we can call the component in the following ways:





A simple Vue component example:

Global Component Example

Register a simple global component runoob and use it:

<

div

id

=

"

app

"

<

runoob

runoob

div

<

script

// Create a Vue app const app = Vue.createApp({}) // Define a new global component named runoob app.component('runoob', { template: '

<

h1

Custom component!

h1

' }) app.mount('#app')

script

Try it »

Next we register another button-counter component; each click increments the counter by 1:

Example

// Create a Vue application

const

app

=

Vue.

createApp

(

{

}

)

// Define a new global component named button-counter

app.

component

(

'button-counter'

,

{

  data

(

)

{

   

return

{

      count

:

0

   

}

 

}

,

  template

:

`

   

<button@click="count++" Clicked{{count}}>

times!

   

button

`

}

)

app.

mount

(

'#app'

)

script

Try it »

Note: In the template, ` is a backtick, not a single quote '.

Component Reuse

You can reuse a component any number of times:

Example

 

 

 

Try it »

Global Components

In the examples above, all our components were globally registered via component.

Globally registered components can be used in the templates of subsequently created app instances, including all child component templates in the root instance's component tree.

Global Component Example

Register a simple global component runoob and use it:

<

div

id

=

"

app

"

<

runoob

runoob

div

<

script

// Create a Vue application const app = Vue.createApp({}) // Define a new global component named runoob app.component('runoob', { template: '

<

h1

Custom component!

h1

' }) app.mount('#app')

script

Try it »

Local Components

Global registration is often not ideal. For example, if you use a build system like webpack, globally registering all components means that even components you no longer use are still included in your final build, unnecessarily increasing the JavaScript users download.

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

const ComponentA = {

  /* ... */

}

const ComponentB = {

  /* ... */

}

const ComponentC = {

  /* ... */

}

Then define the components you want to use in the components option:

const app = Vue.createApp({

  components: {

    'component-a': ComponentA,

    'component-b': ComponentB

  }

})

For each property in the components object, the property name is the custom element name (component-a, component-b), and the property value is that component's options object (ComponentA, ComponentB).

We can also register local components in the instance options, so the component can only be used within this instance:

Local Component Example

Register a simple local component runoobA and use it:

<

div

id

=

"

app

"

<

runoob-a

runoob-a

div

<

script

var runoobA = { template: '

<

h1

Custom component!

h1

' } const app = Vue.createApp({ components: { 'runoob-a': runoobA } }) app.mount('#app')

script

Try it »

Single File Component (.vue file)

Using single file components better organizes and manages Vue components; a component usually consists of three parts: template, script, and style.

Example

<

template

<

div

<

p

{

{

message

}

}

p

<

button

@

click

=

"increment"

Increment

button

div

template

<

script

export

default

{

data

(

)

{

return

{

message

:

'Hello from MyComponent'

,

      count

:

0

   

}

;

 

}

,

  methods

:

{

    increment

(

)

{

     

this

.

count

++;

   

}

 

}

}

;

script

<

style scoped

/* Component private styles */

p

{

  color

:

blue

;

}

style


Prop

A prop is a custom attribute used by child components to receive data passed from the parent component.

The parent component passes data to the child component through props, and the child component must explicitly declare the "prop" using the props option:

Prop Example

<

div

id

=

"

app

"

<

site-name

title

=

"

Google

"

site-name

<

site-name

title

=

"

Runoob

"

site-name

<

site-name

title

=

"

Taobao

"

site-name

div

<

script

const app = Vue.createApp({}) app.component('site-name', { props: ['title'], template: `

<

h4

{{ title }}

h4

` }) app.mount('#app')

script

Try it »

A component can have any number of props by default, and any value can be passed to any prop.

Dynamic Props

Similar to binding an HTML attribute to an expression with v-bind, you can also dynamically bind a prop's value to the parent component's data with v-bind. Whenever the parent's data changes, the change is propagated to the child component:

Prop Example

<

div

id

=

"

app

"

<

site-info

v-for

=

"

site in sites

"

:id

=

"

site.id

"

:title

=

"

site.title

"

site-info

div

<

script

const Site = { data() { return { sites: [ { id: 1, title: 'Google' }, { id: 2, title: 'Runoob' }, { id: 3, title: 'Taobao' } ] } } } const app = Vue.createApp(Site) app.component('site-info', { props: ['id','title'], template: `

<

h4

{{ id }} - {{ title }}

h4

` }) app.mount('#app')

script

Try it »

Prop Validation

A component can specify validation requirements for props.

To customize the prop validation, you can provide an object with validation requirements for the value in props, instead of a string array. For example:



Vue.component('my-component', {

  props: {

    // Basic type checking (`null` and `undefined` pass any type validation)

    propA: Number,

    // multiple possible types

    propB: [String, Number],

    // Required string

    propC: {

      type: String,

      required: true

    },

    // number with default value

    propD: {

      type: Number,

      default: 100

    },

    // object with default values

    propE: {

      type: Object,

      // Object or array defaults must be obtained from a factory function

      default: function () {

        return { message: 'hello' }

      }

    },

    // Custom validation function

    propF: {

      validator: function (value) {

        // This value must match one of the following strings

        return ['success', 'warning', 'danger'].indexOf(value) !== -1

      }

    }

  }

})

When prop validation fails, Vue (in the development build) will produce a console warning.

type can be the following native constructors:

type can also be a custom constructor, detected with instanceof.