Vue2.0 Learning (ii)-Global API

Source: Internet
Author: User

Vue2.0 Learning (ii)-Global Apigithub source code https://github.com/sunnyguyan/VueDemo1.Vue.directive custom Directive One, what is the global API?

The global API is not in the constructor, but rather declares the global variables or defines some new features directly on the Vue, and Vue has built in some global APIs, such as the instruction Vue.directive we are going to learn today. The simple thing to say is to define the new functionality with the API functions that Vue provides to us outside the constructor

Second, vue.directive custom instructions

We learned about internal directives in the first quarter, and we can define some of our own directives, such as defining a V-dire directive to make text green.

Before customizing the instructions we write a small function, on the page there is a number of 10, the number below a button, we each click the button, the number plus 1.

Code

HTML code

<div id="app">        <div v-dire="color" id="demo">            {{num}}        </div>        <div>            <button @click="add">Add</button>        </div>    </div>

JS Code

var app=new Vue({    el:‘#app‘,     data:{         num:10,         color:‘green‘         },        methods:{          add:function(){             this.num++;          }      }  })

Having written this function, we now define a global directive for ourselves. We use vue.directive here ();

Vue.directive(‘jsdire‘,function(el,binding,vnode){        el.style=‘color:‘+binding.value;});
Iii. three parameters passed in a custom directive

El: The element that the directive binds to, which can be used to manipulate the DOM directly
Binding: An object that contains a lot of information about instructions
Vnode:vue compiling the generated virtual node

Iv. life cycle of custom directives
    1. Bind: Called only once, the first time the instruction is bound to the element, this hook function can be used to define a binding initialization action.
    2. Inserted: Called when a bound element is inserted into the parent node (the parent node exists to invoke and does not exist in document)
    3. Update: Called when an element is bound to the template update, regardless of whether the binding value changes. You can ignore unnecessary template updates by comparing the binding values before and after updates
    4. Componentupadted: Called when the template on which the binding element is completing an update cycle
    5. Unbind: Called only once when the instruction is unbound from the element
bind:function(){//被绑定     console.log(‘1 - bind‘);},inserted:function(){//绑定到节点      console.log(‘2 - inserted‘);},update:function(){//组件更新      console.log(‘3 - update‘);},componentUpdated:function(){//组件更新完成      console.log(‘4 - componentUpdated‘);},unbind:function(){//解绑      console.log(‘1 - bind‘);}
2.vue.extend the extension of the constructor, what is Vue.extend?

Vue.extend returns an extended instance constructor, which is the Vue instance constructor with some options preset. Often serving vue.component is used to build components, which can be understood simply as a custom element that encounters the component name as a label in a template, the extended instance constructor is automatically called to produce a component instance and is mounted on a custom element.

Ii. Custom parameter-free label

We imagine a need, the need is this, in the blog page to display the author's network name, and the network name directly have a link address. We wanted only to write in HTML, which was like a custom component, but he didn't pass any parameters, just a static tag.

Our vue.extend is on the scene, so let's use it to write an extension instance constructor. The code is as follows:

var authorExtend = Vue.extend({    template:"<p><a :href=‘authorUrl‘>{{authorName}}</a></p>",    data:function(){    return{          authorName:‘百度‘,          authorUrl:‘http://www.baidu.com‘          }    }});

The label in the HTML is still not working, because the extension instance constructor needs to be mounted, and we mount it again.

new authorExtend().$mount(‘author‘);
Third, mount to the ordinary label

You can also generate an extension instance constructor with an ID or class on an HTML tag, and the code in Vue.extend is the same, but when mounted, we can mount it using a jquery-like selector.

new authorExtend().$mount(‘#author‘);
3.vue.set Global Operations

The function of Vue.set is to manipulate the data, properties, or methods inside the constructor outside the constructor. For example, within the Vue constructor, you define a count of 1, and we define a method outside the constructor to add 1 to the value each time you click a button. You need to use Vue.set.

First, reference the constructor external data:

What is external data, which is not declared in data at the Vue constructor, is declared outside the constructor and then referenced at data. The addition of external data makes the program more flexible, and we can get any form of data we want externally, and then let data refer to it.

To see a simple code:

//在构造器外部声明数据 var outData={    count:1,    goodName:‘car‘};var app=new Vue({    el:‘#app‘,    //引用外部数据    data:outData})
Ii. three ways to change data externally:

1. Change with Vue.set

 function add(){       Vue.set(outData,‘count‘,4); }

2. Use the Vue object method to add

app.count++;

3. Direct operation of External data

outData.count++;

In fact, there are three ways to manipulate external data, and Vue adds a way to manipulate external data.

Third, why should there be vue.set existence?

Because of JavaScript limitations, Vue cannot automatically detect arrays of the following changes.

    • When you set an item directly with an index, Vue does not automatically update for us.

    • When you modify the length of the array, Vue does not automatically update for us.

Look at the code:

<!DOCTYPE html>

At this point our interface is not automatically with the new array, we need to use Vue.set (app.arr,1, ' DDD ') to set the change, Vue will automatically update us, this is the meaning of vue.set existence.

4.Vue life cycle (hook function)

Vue has a total of 10 life cycle functions that we can use to manipulate data or change content at every stage of Vue.

Let's look directly at a piece of code:

<! DOCTYPE html>
5.Template making template A template that is written directly in the options

Write directly behind the template option in the constructor. This is a straightforward way to write, but it is not recommended if the template has too many HTML code.

JavaScript code:

 var app=new Vue({     el:‘#app‘,     data:{         message:‘hello Vue!‘      },     template:`        

Second, write in<template>Template in the tag

This is more like writing HTML code, even if the person who does not write Vue, can also make the page.

    <template id="demo2">             

Three, written in<script>Template in the tag

This method of writing templates allows template files to be imported from outside.

   <script type="x-template" id="demo3">        

This class we learn the template of the three kinds of writing, after learning to VUE-CLI will learn a kind of xxx.vue writing.

6.Component Primary Component I. Global registration component

Global is registered with vue.component outside the constructor, we register now to register a component to experience.

<!DOCTYPE html>

We registered a component in JavaScript and called him in HTML. This is the simplest way to write a component, and it can be placed in the scope of multiple constructors.

Second, local registration components local registration components and global registration components are to the corresponding, locally registered components can only be used in the scope of the component registration, the other scope use is not valid.
<!DOCTYPE html>

From the code you can see that the local registration is actually written in the constructor, but you need to note that the components in the constructor is plus s, and the global registration is not add S.

Iii. differences in components and directives

The component registers a label, and the instruction registers an attribute in the existing tag. In the actual development we still use more components, instructions with less. Because the instructions don't look so good, it's just a personal point of view.

Component Component Props Property settings

The props option is to set and get the property value on the label, for example, we have a custom component, and we want to add a label attribute to it that means that the panda is from China, of course, the Chinese can be replaced by any value. The option to define a property is props.

First, define attributes and get property values

Defining attributes we need to use the props option, plus an array of property names, for example: props:[' here '. Reading the attribute values in the component's template only needs to be in the form of interpolation, for example {{here}}.

<!DOCTYPE html>

The above code defines the panda component and uses the props to set the Here property value, passing the China to component in the here attribute value.

The result of the final output is the panda of the red font from the China.

Second, the property of the "-" approach

We often add '-' to the word when writing attributes, such as:, then we in the props if written props:[' Form-here ' is wrong, we must use the small hump style props:[' Formhere '.

HTML file:

<panda from-here="China"></panda>

JavaScript code:

   var app=new Vue({            el:‘#app‘,            components:{                "panda":{                    template:`<div style="color:red;">Panda from {{ here }}.</div>`,                    props:[‘fromHere‘]                }            }        })
Iii. passing values to components in a constructor

By passing the value of data in the constructor to the component, we just have to bind it. Is the v-bind:xxx we learned in the first quarter.

We look directly at the code:

HTML file:

<panda v-bind:here="message"></panda>

JavaScript files:

      var app=new Vue({            el:‘#app‘,            data:{               message:‘SiChuan‘             },            components:{                "panda":{                    template:`<div style="color:red;">Panda from {{ here }}.</div>`,                    props:[‘here‘]                }            }        })
8.Component Parent-Child component relationships

In actual development we often encounter the need to use other custom components in a custom component, which requires a parent-child component relationship.

First, the constructor external write local registration component

Local components are written inside the constructor, and if the component code is large, it can affect the readability of the constructor, causing drag and error.

We put the code written by the component outside the constructor, or as a separate file.

We need to declare an object, which is the content of the component.

var panda= {   template:`<div>Panda from China!</div>`}

It is OK to refer to the constructor after declaring the object.

components:{    "panda":panda}

Referenced in HTML

<panda></panda>
Nesting of parent-child components

We declare a parent component, such as Panda, and then we add a city component, and we'll see how the code is written.

<!DOCTYPE html>
9.Component Label

The <component></component> tag is a custom label for the Vue framework, and its purpose is to dynamically bind our components and replace different components depending on the data.

    1. We first define three different components outside the constructor, namely COMPONENTA,COMPONENTB and COMPONENTC.
 var componentA={     template:`<div>I‘m componentA</div>`} var componentB={      template:`<div>I‘m componentB</div>`}var componentC={    template:`<div>I‘m componentC</div>`}
    1. We include these three components in the component options of the constructor.
components:{    "componentA":componentA,    "componentB":componentB,    "componentC":componentC,}
    1. We insert component tags in HTML and bind who data, calling different components according to WHO's values.
<component v-bind:is="who"></component>

This is the basic use of our component labels. We raise the following, add a button to the page, each point below the replacement of a component.

<! DOCTYPE html>

Vue2.0 Learning (ii)-Global API

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.