Come on! Complete Vue components in one article!

Keywords: Front-end Vue Attribute JSON PHP

By Jeskson

Source: front end tavern of dada

Overview of Vue components

What is a component? Understand the analysis of component objects, the data properties of Vue components, and what is the principle of props to transfer data.

Events Communications

How to understand parent-child component event communication, and how to deal with non parent-child component event communication.

What the hell is component type

How is it called dynamic? Why is it dynamic? How to understand recursion.

Understanding of Vue components

Vue's understanding can be found in my last article, vue.js - a detailed explanation of three popular frameworks, Vue - a quick and advanced front-end Tyche - Vue foundation. What is a component? A component is a part of its encapsulated function. What you write is called a component. What others write is called a plug-in. The use of a component is one of the powerful functions of vue.js. The emergence of a component is to improve the reusability of the code. A component is a Part of it is complete. If you want to use it, you can put it on any of your own projects to reduce the repetition of code.

It can be imported directly where you want to use it. Does it reduce repetitive development? You can put the code of components into corresponding files according to the split form of template, style and script.

What is template? It is a template, which declares the mapping relationship between the data and the dom finally presented to the user. What is the initialization data? The initial data state of a component is usually a private state for reusable components. Method is a method to operate on data and receive external parameters. Components transfer and share props through parameters. Parameters are one-way binding or two-way binding by default.

Callback function, a component can trigger multiple callback functions, created(), attached(), destroyed().

Vue components, global and local registration

Global registration file, created by Vue.component('component name ', {component parameter})

<body>
 <div id="app">
  <my-component></my-component>
 </div>
 <script src="https://unpkg.com/vue"></script>
 <script>
 // Create global components
 Vue.component('my-component",{
 // template: HTML code structure of component
 template: '<div>this is dada</div>'
});
// Vue instance object
var vm = new Vue({
 el: '#app'
});
</script>
</body>

For local registration components, not every component needs to be registered globally. You can also directly use the content keyword to register custom components in the constructor of the vue instance object.

<div id="app">
 <local-component></local-component>
</div>

<script src="https://unpkg.com/vue"></script>
<script>
// Vue instance UI is small
var vm = new Vue({
 el: '#app',
 // Create local components
 components: {
  'my-components': {
   template: '<div>this is my</div>'
   }
  }
 }
});

First, create the local component object, then register the local component object in the Vue constructor, and finally use the local component.

<div id="app">
 // By default, the ui is automatically converted to a dash using the camel notation
 <local-component></local-component>
</div>

<script src="https://unpkg.com/vue"></script>

<script>
// Create local components
const localComponent = {
 template: '<div>this is da</div>'
}

// vue instance object
var vm = new Vue({
 el: '#app',
 // Create a local component that is only valid for the current vue instance object
 components: {
  // Registration component
  localcomponent
 }
});
</script>
var vm = new Vue({
 el: '#app',
 // Create local components
 components: {
  // Registration component
  'my-component': localComponent
 }
});

Analysis of component objects

The vue component is a vue instance:

// Custom components
var dada = Vue.component('my-component', {
 template: '<h1>dada</h1>'
});

A component can only have a single root element, which is OK:

// custom
const dada = Vue.component('my-component', {
 template: `
  <div>
   <span>Dada front end</span>
   <p> this is da</p>
  </div>
  `
});

Use the template tag in the component:

<div id='app'>
 <h1>my-component</h1>
 <my-component></my-component>
</div>

<template id="my">
 <div>this is dada</div>
 <p>this is dadadada</p>
</template>

<script..></script>

<script>
 // Custom components
 const my = Vue.component('my-component", {
  template: '#my'
 });
 // vue instance object
 var vm = new Vue({
  el: '#app'
 });
</script>

// Program errors will occur
 because vue A component can only have one root element.

assembly template Property contains div And P Two elements
<template id="my">
 // Component can only have one root element
 <div>
  <div>da</div>
  <p>da</p>
 </div>
</template>

// Success

data attribute in vue component

In a component, you can use any valid Vue instance object property. The data property is the responsive data available to the Vue component, which is the data object of the Vue instance. After the instance is created, the user can access the original data object through vm.$data, and the Vue instance also represents all the properties of data.

That is, vm.a is equivalent to vm.$data.a. properties starting with "_" or "$" will not be proxied by Vue instance, because they may conflict with Vue built-in properties and api methods.

// Create an instance
var vm = new Vue({
 data: data
})
vm.a // => 1
vm.$data === data // => true

// data in Vue.extend()
var Component = Vue.extend({
 data: function() {
  return { a: 1 }
 }
})

The data property must be declared as a function that returns an initial data object.


<div id="app">
 <h1>my-component</h1>
 <my-component></my-component>
 <h2>my</h2>
 <my-component></my-component>
</div>

<template id="my">
 <div>
  <div>this is my</div>
  <p>this is da</p>
  <p>{{message}}</p>
  <button @click="message = 'update message'">
  //modify
  </button>
 </div>
</template>

<script src="https://unpkg.com/vue"></script>

<script>
 var data={
  message: 'global'
 }
 // Global component
 const my = Vue.component('my-component', {
  template: '#my',
  // The data attribute represents the data information used by the current component
  // The data attribute must be in the form of a callback function, in which you want to return an object
  data: function() {
   return data;
  }
});
 // Vue instance object
 var vm = new Vue({
  el: '#app'
 });
</script>
// Global component
const my = Vue.component('my-component',{
 template: '#my',
 // The data attribute indicates the current component usage data information
 // The data attribute must be in the form of a callback function, in which you want to return an object
 // The data property should return a common object
 data: function() {
  return {
   message: 'component-message'
  };
 }
});

props passing data

Props is a field in component data, which is used for communication between parent component and child component. Child component uses props to obtain data of parent component. Props can be literal syntax, dynamic syntax, binding modifier, etc.

Props literal quantity: the child component declares the data of the parent component to be received through props. The parent component uses the child component to pass the data for the child component through HTML attribute.

Sub components:

const my = {
 // props: claim to receive parent component data
 props: ['message'],
 // Same as data.
 template: '<span>{{message}}</span>'
}

Parent component:

<my-component message="message from parent by props">
<my-component>
const my = {
 props: ['myMessage'];
 template: '<span>{{message}}</span>'
}
<my-component my-message="hello"></my-component>
Sub components props Specified data
Vue.component("my-component",{
 props: ['message'],
 template: '<span>{{message}}</span>'
});
<my-component alt="this is add"></my-component>

Dynamic syntax:

<div id="app">
 <my-component v-bind:message="message">
 </my-component>
 <my-component :message="message">
 </my-component>
</div>

The v-bind instruction binds HTML attributes to an expression and uses the v-bind instruction to bind dynamic props to the data of the parent component.

var vm = new Vue({
 el: '#app',
 data: {
  user: {
   name: 'test',
   age: '12'
  }
 }
});

<div id="app">
<my-component :user="user"></my-component>
<my-component user="user"></my-comoponent>
</div>

Binding modifier

When the properties of the parent component change, it is passed to the child component

// Default one way binding
<child :message="parentMessage"></child>
// Bidirectional binding
<child :message.sync="parentMessage"></child>
// Unidirectional binding
<child :message.once="parentMessage"></child>
// Modifying props in a child component affects the state of the parent component
<div id="example">
 <input type="text" v-model="info.name"/>
 <child v-bind:msg.once = "info"></child>
</div>
<script src="vue.js"></script>

<script>
// Create root instance
var vm = new Vue({
 el: '#example',
 data: function() {
  return {
   info: {
   name: 'hello'
   }
  }
 },
 components: {
  'child': {
   //Statement props
   props: ['msg'],
   template: '<div>{{msg.name}}</div>'
  }
 }
});
</script>
Vue.component('example', {
 props: {
  propsA: 'null',
  // Multiple types
  propM: [String, Number],
  // Must be a string
  propB: {
   type: String,
   required: true
  },
  propc: {
   type:Number,
   default: 100
  },
  propD: {
   type: Object,
   default: function() {
    return {msg: 'hello'}
   }
  },
  // Specify props as a two-way binding
  propE: {
   twoWay: true
  },
  propF: {
   validator: function() {
    return value > 10
   }
  }
 });

type: string,number,boolean,object,function,array

type can be a custom constructor.

Define a commerce() function for props

Vue.component('example', {
props: {
 // Transformation function
 propG: {
  coerce: function(val) {
   return val+''
  }
 },
 propH: {
  coerce: function(val){
   return JSON.parse(val)
  }
 }
}
})

Event communication

In event communication of parent-child components, some attributes of elements will be used in HTML. The parent component passes data to the child component through props, and the child component sends messages to the parent component through events.

The child component needs some data. You can define a props internally. The parent component passes the data attribute to the data attribute of the child component.

// Parent component passes data to child component
<my-component :item="users"></my-component

Vue.component('example',{
 template: `<div><button @click="myclick"></button></div>`,
 methods: {
  myclick: function() {
  }
 }
});

Parent component passes data to child component

A vue custom event mechanism can be used by a child component to send messages to the parent component.

The child component mainly triggers events to the parent component by using $emit.

The parent uses the $on or v-on instructions to listen for events triggered by the child and receive messages sent by the child.

<div id="app">
 <my-component @childevent="handleEvent"></my-component>
</div>
Vue.component('my-component',{
template: '#my-component',
props: ['value'],
methods: {
 emitEvent: function() {
  console.log('child component click event');
  this.$emit('childevent');
 }
}
});
Vue.component('my-component',{
template: '#my-component',
props: ['value'],
methods: {
 emitEvent: function() {
  console.log('child component click event');
  this.$emit('childevent');
 }
}
});
emitEvent: function() {
 this.$emit('childevent','Additional data')
}
handleEvent: function(){
 console.log(arguments[0]);
}

The child sends a message to the parent. Parent $on or v-on listens for events triggered by child components and receives messages sent by child components.

<div id="app">
// Use components
<my-component :message="message" @my-component-event="handleMyComponentEvent">
</my-component>
<p>message==={{message}}</p>
</div>

<template id="my">
<div>
<p>{{message}}</p>
<p>
 <button @click="handleClick"></button>
</p>
</div>
</template>

<script>
const myComponent={
template: '#my',
props:['message'],
methods:{
handleClick: function(){
this.$emit('my-component-event','updata');
}
}
};
// Vue instance object
var vm = new Vue({
el: '#app',
data: {
message: 'from parent'
},
// Registration component
components: {
 myComponent
},
// Method
methods: {
 // Receive sub component definition event handling
 handleMyComponentEvent: function(param){
 this.message=arguments[0];
 }
}
});

Event communication by non parent child components

The parent component passes data to the child component through props, and the child component triggers dynamic modification events to the parent component through custom events.

Communication between non parent and child components

In the child component, access the parent component or root component instance object of the current component by using $parent or $root.

this.$parent parent parent this.$root root component


var vm = new Vue({
 el: '#app',
 data: {
  message: 'message'
 },
 components: {
  childComponent
 }
});

const childComponent={
 template:'',
 methods:{
 updateRootMessage: function(){
  this.$root.message='message from child';
 }
}
};

The parent component accesses the child component, and uses the ref attribute to access the child component through this.$refs

<div id="app">
 <child-component ref="childComponent">
 </child-component>
</div>

var vm = new Vue({
 el: '#app',
 components: {
  childComponent
 },
 methods: {
  updateChild: function(){
   this.$refs.childComponent.message="from parent";
  }
 }
});

Event bus mechanism

Monitor the subscription on and trigger the exit. Use the on method to listen to an event, use the exit method to trigger the event, and call the on method callback function at the same time, thus completing an event trigger.

var dada = new Vue()
// Trigger events in component a
dada.$emit('id-selected',1)
// Trigger the listening event in the function created by b
dada.$on('id-selected', function(id){
})

Create event bus object

var dada = new Vue()

Listen for events triggered by event bus

dada.$on

Trigger custom event

dada.$emit

<div id="app">
<child1-component></child1-component>
<child2-component :message="message" ref="child2">
</child2-component>
</div>

<template id="child1">
<div>
<button @click="updateChild2">da</button>
</div>
</template>

<template id="child2">
<div>
message={{message}}
<p>{{name}}</p>
</div>
</template>

<script src="https://Unpkg. COM / Vue "> content of update 2 < / script >

<script>
const dada = new Vue();
// Creating components
const child1Component={
 template: '#child1',
 methods: {
  updaeChild2: function(){
   // Use event bus to trigger custom events
   dada.$emit('child1-event','update name from child1');
  }
 }
};

const child2Component = {
 template: '#child2',
 props: ['message'],
 data: function() {
  return {
   name: 'child2'
  };
 },
 created: function() {
 // Keep current vue component object
 const app = this;
 // Listen for events triggered by the event bus
 bus.$on('child1-event', function(param){
  console.log('capture');
  app.name = param;
 });
}
};
</script>

❤ don't forget to leave your footprints of learning [like + collect + comment]

Author Info:

[author]: Jeskson Original public address: dada's front bar. [welfare]: the public number replied to "information" to send the self study material gift package (enter group to share, want to say, ha, see if I have). [reprint description]: please explain the source of reprint, thank you for your cooperation! ~

Large front-end development, positioning front-end development technology stack blog, PHP background knowledge point, web full stack technology field, data structure and algorithm, network principle, etc. are easy to understand and presented to small partners. Thank you for your support, thank you very much!!!

If the content of this number is not in place (for example, involving copyright or other issues), please contact us in time for rectification, and we will deal with it as soon as possible.

Please praise! Because your approval / encouragement is the biggest driving force of my writing!

Welcome to your attention. Dada CSDN!

This is a blog with quality and attitude

Posted by verdrm on Wed, 11 Dec 2019 07:10:37 -0800