I. Component Creation
Create a new component under the components folder, runoob.vue
<template> <div>Custom Components</div> </template> <script> export default { data () { return { } } } </script>
II. Component Reference
1. Import component runoob.vue through import
import runoob from '@/components/runoob.vue'
2. Register the component under components
components: {
runoob
}
3. Reference in Labels
<runoob></runoob>
Complete examples:
<template> <div id="app"> <runoob></runoob> </div> </template> <script> import runoob from '@/components/runoob.vue' export default { data () { return { } }, components: { runoob } } </script>
Operation results:
3. Custom Properties of Components
1. Prop passes attribute values
prop is a custom property used by the parent component to pass data (data is passed to the child component through props)
components/runoob.vue file:
<template> <div :style="{ color: col }">Custom Components</div> <!-- Applying the received data to tag attributes --> </template> <script> export default { data () { return { } }, props: { col: { type: String, default: '#000' } } // Receive incoming data } </script>
View/demo.vue file:
<template> <div id="app"> <runoob col="red"></runoob> <!-- Customize attribute values in tags as data to pass --> </div> </template> <script> import runoob from '@/components/runoob.vue' export default { data () { return { } }, components: { runoob } } </script>
Operation effect:
2. Prop validates attribute values
props: { col: { type: String, default: '#000' } }
The type here can be the following native constructor:
- String
- Number
- Boolean
- Array
- Object
- Date
- Function
- Symbol
When Prop validation fails, Vue (build version based on development environment) generates a console warning
IV. Component Customization Events
The parent component uses props to pass data to the child component, but if the child component wants to pass data back, it needs to use custom events.
1. $emit(eventName) trigger event
components/runoob.vue file:
<template> <div :style="{ color: col }" @click="doWhat">Custom Components</div> <!-- Applying incoming data to tags --> <!-- Binding Click Events doWhat --> </template> <script> export default { data () { return { } }, methods: { doWhat () { this.$emit('myMethod') } }, // doWhat trigger myMethod Event props: { col: { type: String, default: '#000' } } // Receive incoming data } </script>
View/demo.vue file:
<template> <div id="app"> <runoob col="red" @myMethod="sayHello"></runoob> <!-- Customize attribute values in tags as data to pass --> </div> </template> <script> import runoob from '@/components/runoob.vue' export default { data () { return { } }, methods: { sayHello () { alert('Hello!') } }, // trigger myMethod Events are called sayHello components: { runoob } } </script>
Operation effect: