bring it on! Article thoroughly to get Vue assembly!

file

Author | Jeskson

Source | Dada front-end bistro

Overview Vue assembly

What are the components of it, understand component object of analysis, data attributes Vue assembly, the principle of props to transfer data in the end what it is.

Those things events communication

How to understand the components of event communication and his son, and his son encountered a non-event communication components how to deal with.

What the hell is the component type

Custom Component way binding v-model, dynamic components, and how called dynamic, why is it dynamic, recursive components, how to understand recursion.

Learn Vue assembly

Vue understanding, I can find a vue.js- explain what the three popular frameworks VUE_ quickly advanced front-end large coffee -Vue basis, component is the component that is written in their own part of the package good function, write your own called components, written by someone else called the use of plug-in components, is one of vue.js powerful, has a component is to improve code reusability, components are part of a complete good, if you want to use, you can put you own up to any project, reduce duplication of writing code.

Can be introduced directly to where you want to use is not reduced repetitive development, code components can be split according to the form template, style, script, and put the corresponding file.

What template that? It is a template (template), the template is declared data and the final presentation to the mapping relationship between the user's dom, what initialization data is data? An initial data state of a component, the component can be reused for it, usually a private state, the method methods is a method of operating a data receiving an external parameter between the components to transfer data and share props parameter, The default parameter is a one-way binding, can be two-way binding.

Callback function, a component can trigger many callbacks, created (), attached (), destroyed ().

Vue components, global registration and partial registration

Global register file, create Vue.component ( 'component name', component parameters {}) mode

<body>
 <div id="app">
  <my-component></my-component>
 </div>
 <script src="https://unpkg.com/vue"></script>
 <script>
 // 创建全局组件
 Vue.component('my-component",{
 // template: 组件的HTML代码结构
 template: '<div>this is dada</div>'
});
// Vue实例对象
var vm = new Vue({
 el: '#app'
});
</script>
</body>

Local registration component, not every component is required global register may be directly in the constructor vue instance of an object, a compontent keywords registered custom components.

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

<script src="https://unpkg.com/vue"></script>
<script>
// Vue实例UI小
var vm = new Vue({
 el: '#app',
 // 创建局部组件
 components: {
  'my-components': {
   template: '<div>this is my</div>'
   }
  }
 }
});

First, create a local component object, and then register Vue constructor registered local component object, and finally the use of local components.

<div id="app">
 // 在默认情况,使用camel标记法将ui自动转换为短横线形式
 <local-component></local-component>
</div>

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

<script>
// 创建局部组件
const localComponent = {
 template: '<div>this is da</div>'
}

// vue实例对象
var vm = new Vue({
 el: '#app',
 // 创建只对当前vue实例对象有效的局部组件
 components: {
  // 注册组件
  localcomponent
 }
});
</script>
var vm = new Vue({
 el: '#app',
 // 创建局部组件
 components: {
  // 注册组件
  'my-component': localComponent
 }
});

Analysis of Component Object

vue vue is a component instance:

// 自定义组件
var dada = Vue.component('my-component', {
 template: '<h1>dada</h1>'
});

Assembly only has a single root element, this line also:

// 自定义
const dada = Vue.component('my-component', {
 template: `
  <div>
   <span>达达前端</span>
   <p> this is da</p>
  </div>
  `
});

Using the template tag assembly:

<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>
 // 自定义组件
 const my = Vue.component('my-component", {
  template: '#my'
 });
 // vue实例对象
 var vm = new Vue({
  el: '#app'
 });
</script>

// 会出现程序错误
因为vue组件只允许有一个根元素。

组件template属性中包含div与P两个元素
<template id="my">
 // 组件只允许有一个根元素
 <div>
  <div>da</div>
  <p>da</p>
 </div>
</template>

// 成功

components data property vue

In the assembly, any valid object property instance Vue. The data property is responsive Vue available component data, which is an example of the data object Vue. After you create instances, users can vm. $ Data access to the original data object, Vue examples also represent all the attributes of data.

That is equivalent to vm.a vm. $ Data.a, a "_" or "$" at the beginning of the attributes are not agent Vue example, since they may conflict and the built-in property and Vue api method.

// 创建一个实例
var vm = new Vue({
 data: data
})
vm.a // => 1
vm.$data === data // => true

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

property return data must be declared as a function of the 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'">
  修改
  </button>
 </div>
</template>

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

<script>
 var data={
  message: 'global'
 }
 // 全局组件
 const my = Vue.component('my-component', {
  template: '#my',
  // data属性表示当前组件使用的数据信息
  // data属性必须是回调函数形式,在回调函数中要返回对象
  data: function() {
   return data;
  }
});
 // Vue实例对象
 var vm = new Vue({
  el: '#app'
 });
</script>
// 全局组件
const my = Vue.component('my-component',{
 template: '#my',
 // data属性表示当前组件使用额数据信息
 // data属性必须是回调函数形式,在回调函数中要返回对象
 // data属性应该返回一个都有的对象
 data: function() {
  return {
   message: 'component-message'
  };
 }
});

Data transfer props

Parent props used for communication between components and subcomponents, is a field in the data component, subassembly props used to obtain data parent element, props may be a literal syntax, grammar dynamic binding modifiers and the like.

props literal, parent component subassembly data to be received by the props statement, the parent subassembly components used to pass data to the HTML attribute through a sub-assembly.

Subassembly:

const my = {
 // props:声明接收父组件数据
 props: ['message'],
 // 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>
子组件props指明数据
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>

v-bind HTML directive property is bound to one expression, using v-bind props instruction dynamically bind data to 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 parent component attribute changes, will be passed to subassembly

// 默认单向绑定
<child :message="parentMessage"></child>
// 双向绑定
<child :message.sync="parentMessage"></child>
// 单向绑定
<child :message.once="parentMessage"></child>
// 在子组件中修改props都会影响父组件的状态
<div id="example">
 <input type="text" v-model="info.name"/>
 <child v-bind:msg.once = "info"></child>
</div>
<script src="vue.js"></script>

<script>
// 创建根实例
var vm = new Vue({
 el: '#example',
 data: function() {
  return {
   info: {
   name: 'hello'
   }
  }
 },
 components: {
  'child': {
   //声明props
   props: ['msg'],
   template: '<div>{{msg.name}}</div>'
  }
 }
});
</script>
Vue.component('example', {
 props: {
  propsA: 'null',
  // 多种类型
  propM: [String, Number],
  // 必须是字符串
  propB: {
   type: String,
   required: true
  },
  propc: {
   type:Number,
   default: 100
  },
  propD: {
   type: Object,
   default: function() {
    return {msg: 'hello'}
   }
  },
  // 指定props为双向绑定
  propE: {
   twoWay: true
  },
  propF: {
   validator: function() {
    return value > 10
   }
  }
 });

type类型:string,number,boolean,object,function,array.

The type can be a custom constructor.

Props to define a coerce () function

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

Incident communication

Sons event communication component will be used in HTML will have some of the attributes of the elements, pass data to the parent component by The props subassembly, the subassembly sends a message to the parent component through events.

A data sub-assembly needs to be a definition of The props, parent component passing data to the data property attributes within the subassembly.

// 父组件向子组件传递数据
<my-component :item="users"></my-component

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

Parent components pass data to subassembly

Sub-assembly component sends the message to the parent can use custom vue event mechanism.

The main sub-components by using $ emit a trigger event to the parent component.

Parent component using $ on or v-on instruction to listen to events triggered by the sub-assemblies, subassemblies and receive messages sent.

<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','附加数据')
}
handleEvent:function(){
 console.log(arguments[0]);
}

Send a message to the parent sub-assembly components. Events parent component $ on or v-on monitor subcomponents triggered, the message sent by the receiving sub-assembly.

<div id="app">
// 使用组件
<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实例对象
var vm = new Vue({
el: '#app',
data: {
message: 'from parent'
},
// 注册组件
components: {
 myComponent
},
// 方法
methods: {
 // 接收子组件定义事件处理
 handleMyComponentEvent: function(param){
 this.message=arguments[0];
 }
}
});

Sons components of non-event communication

Transfer data to the parent component sub-assemblies by props, sub-assemblies to dynamically modify the trigger event to the parent component through custom events.

Communication between components of a non-father and son

Subassembly, or by using $ parent $ root, or root access to the parent object of the current instance of the component assembly.

this. $ parent the parent component of
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';
 }
}
};

Access parent component sub-assemblies, using the ref attribute, visit subassembly by 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

Subscribe monitor on, triggering emit. By on way to listen for an event, use emit method to trigger this event, while calling this method on the callback function, thus completing a triggering event.

var dada = new Vue()
// 触发组件a中的事件
dada.$emit('id-selected',1)
// 触发b创建的函数中监听事件
dada.$on('id-selected', function(id){
})

Create an event bus objects

var dada = new Vue()

Listening to events triggered by an event bus

dada.$on

Trigger custom events

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">更新2的内容</script>

<script>
const dada = new Vue();
// 创建组件
const child1Component={
 template: '#child1',
 methods: {
  updaeChild2: function(){
   // 使用事件总线触发自定义事件
   dada.$emit('child1-event','update name from child1');
  }
 }
};

const child2Component = {
 template: '#child2',
 props: ['message'],
 data: function() {
  return {
   name: 'child2'
  };
 },
 created: function() {
 // 保留当前vue组件对象
 const app = this;
 // 监听事件总线触发的事件
 bus.$on('child1-event', function(param){
  console.log('捕获');
  app.name = param;
 });
}
};
</script>

❤️ Do not forget to leave your footprints learning [+ collection point Like Comments +]

Author Info:

[Author]: Jeskson
[original] Public number: Dada front-end bistro.
[Welfare]: No public reply "Information" self-study materials sent to spree (into the group to share what you want to say Ha, I did not see)!
[Reserved] Description: reproduced please indicate the source, thank you! ~

Large front-end development, front-end development positioning technology stack blog, PHP background knowledge, web full stack technology fields, data structures and algorithms, and so easy to understand network theory is presented to the junior partner. Thank you support, courtesy of love! ! !


If this number of local contents do not get bits (for example: to copyright or other problems), please contact us for rectification can be timely and will be processed in the first time.


Please thumbs up! Because you agree / encouragement is the greatest power of my writing!

Welcome attention to Dada 's CSDN!

This is a quality, attitude blog

Front-end technology stack

Guess you like

Origin www.cnblogs.com/dashucoding/p/12026297.html