VueAPI official document: cn.vuejs.org/v2/api/

Vue provides a lot of API, but commonly used on the following four, we will be from their functional description, use scenarios, use ways of several aspects of a simple understanding of how to use, if you have the ability of students can go to see the source code and specific implementation!

Set, delete

Functional description

Action: Changes the properties of reactive data and ensures that the new property is also responsive, triggering an update of the view. Set is used to add new properties to reactive objects. Delete is used to delete a property of an object!

The usage of set and delete is basically the same, here we will take set as an example, say its usage!

1 / / usage
Vue.set( target, key, value )
Vue.delete( target, key )
2 / / usage
vm.$set( target, key, value )
vm.$delete( target, key )
Copy the code

Description:

  • Target: Indicates the target object
  • Key: indicates the name of the attribute to be added
  • Value: indicates the value of the attribute to be added

Note that in vue2.2 and later versions, the key value of delete supports Array + index (list[1]).

Usage scenarios

If we have a list of items, each list contains the name of commodity, commodity prices and the number of users to buy goods, the three fields, but on the server side for the list of goods is not the concept of the number of users to buy goods, so the server can return to the name and the price of a commodity, as for the number of the column need to add it yourself.

Example:

<div id="app">
    <ul>
        <li v-for="(item, index) in goods" :key="index">
            <span>. Name: {{item name}}</span>
            <span>Price: {{item. Price. ToFixed (2)}}</span>
            <span>Quantity: {{item. Num}}</span>
            <br>
            <input type="button" value="+" @click="item.num += 1">
            <input type="button" value="-" @click="item.num -= 1">
        </li>
    </ul>
</div>

<script>
    var vm = new Vue({
        el: '#app'.data: {
            goods: []
        },
        created () {
            let $this = this;
            setTimeout(() = > {
                $this.goods = [
                    {
                        name: 'android'.price: 12.99
                    },
                    {
                        name: 'IOS'.price: 13.99
                    },
                    {
                        name: 'javaScript'.price: 14.99}]; $this.goods.forEach(item= > {
                    // item.num = 1;
                    vm.$set(item, 'num'.1);
                    // Vue.set(item, 'num', 1);
                });
            }, 3000); }});</script>
Copy the code

In the created function hook, where data is mounted, we use a timer of 3 seconds to simulate a real network request. By default, we pass a num property to each object of goods using vue. Set. And do the click event for the input button, to achieve the real-time update of the number of requirements!

Note: the final result of vm.$set and vue. set are the same, delete is similar to set.

filter

Vue filters are divided into global filters and local filters!

Use of filters

When defining a filter, can be in double braces interpolation {{message | filter}} or v – bind expression (the latter since 2.1.0 + support) tail, through | “pipe symbol” to use our definition of the filter.

Creating a Filter

There are two ways to define a filter:

Defining global filters

  1. Filters are defined globally before the Vue instance is created, as shown below. The filters defined this way are used globally.
// Define filters globally before creating Vue instances
Vue.filter('filterName'.function (value) {...return retValue;
});

newVue({... })Copy the code

Defining local filters

  1. Use the Filters option to define local filters, as shown below. Filters defined this way are used in single-file components.
filters: {
  filterName: function (value) {...returnretValue; }}Copy the code

Usage scenarios

A filter can be used for text formatting. Text formatting means taking some text (user input, server return, or whatever you want to text) and rearranging it in the format you want.

If we want to capitalize the first letter of the user’s English word and make the rest of the word lowercase, I can define a global filter if I want to use it globally!

Example:

<div id="app">
      <p>{{ message|titleCase }}</p>
    </div>
    
    <script type="text/javascript">
      
      // Define a global titleCase filter
      Vue.filter('titleCase'.function(value){
        // Turns all the characters of the string to lowercase and converts them to a character array based on Spaces
        var arr = value.toLowerCase().split("")
        
        // Go through the group
        for(var i=0; i<arr.length; i++){
          // Make the first character uppercase and the rest lowercase
          arr[i] = arr[i].slice(0.1).toUpperCase() + arr[i].slice(1).toLowerCase();
        }
        // Return with space
        return arr.join("");
      })
      
      var app = new Vue({
        el:"#app".data: {message: "config is an object containing vue application global configurations. "}})</script>
Copy the code

Case 2:

  • Local filter is used to capitalize the license plate number entered by the user
<div id="app">
    <p>John a. {{plateNum | plateNumFilter}}</p>
    <br>
    <input type="text" v-model="plateNum">
</div>

<script>
    var vm = new Vue({
        el: '#app'.data: {
            plateNum: ' '
        },
        filters: {
            // Val is the bound text, in this case plateNum
            plateNumFilter: function (val) {
                // The content of return is the content after rearranging through the plateNumFilter filter
                return val.toUpperCase().substring(0.5); }}});</script>
Copy the code

At the same time, the filter can receive parameters (the value of the filter total receive expression as the first parameter) and can be concatenated (multiple filters). Let’s change the above example to make the filter more focused and the string interception reusable.

< p > shan a. {{plateNum | toUpperCaseFilter | substringFilter (5)}}</p>

Vue.filter('toUpperCaseFilter'.function (val) {
    return val.toUpperCase();
});
Vue.filter('substringFilter'.function (val, endNum) {
    return val.substring(0, endNum);
});
Copy the code

We created two filters, toUpperCaseFilter will convert the text content to uppercase, substringFilter will intercept the fixed length string, so that their function becomes more pure, can be better reuse, which is also the one we recommend to write. The combination of these two filters is used to achieve our purpose.

Note:

When there are local and global filters with the same name, they will be called according to the proximity principle, that is, the local filter is called before the global filter!

directive

Directive to create

Directive, like filter, can be defined in two ways:

Global custom directives

  1. Before creating a Vue instance, a directive is defined globally via vue. directive, as shown below. Directives defined this way are used globally.
Vue.directive('directiveName', {... })newVue({... })Copy the code

Local custom instructions

  1. Use the directives option to define local directives, as shown below. Directives defined this way are used in single-file components.
directives: {
  directiveName: {... }}Copy the code

Functional description

Directive is a custom directive in Vue. V-model and V-show learned before are all default directives provided by Vue. When the default directives provided by Vue are insufficient to meet our needs, we can add custom directives through directive.

Usage scenarios

We can assume that Vue does not provide a V-show directive. We can use directive to simulate what V-show does. We can create a V-demo directive that controls the DOM display and hide based on the conditions we pass in. Let’s first look at how this requirement should be implemented.

<div id="app">
    <span v-demo="isShow">Hello v-demo</span>
</div>

<script>
    Vue.directive('demo', {
        bind: function (el, binding, vnode, oldVnode) {
            el._originalDisplay = el.style.display;
            if(! binding.value) { el.style.display ='none'; }},update: function (el, binding, vnode, oldVnode) {
            if(! binding.value === ! binding.oldValue)return;
            binding.value ? el.style.display = el._originalDisplay : el.style.display = 'none'; }})var vm = new Vue({
        el: '#app'.data: {
            isShow: true}});</script>
Copy the code

We can control the display and hide of the Hello V-demo by controlling isShow, which is relatively simple and cannot be rendered in real time.

Directive creation is a little more complicated. When a directive is created using the vue. directive method, it takes two arguments. The first argument is the directive name. For example Vue. Directive (‘ demo ‘{… }) in this way, we add a directive called demo, which can be used in the DOM v-demo.

The second argument is an object that provides several function hooks to describe the states created, updated, and destroyed by the directive. It also provides some parameters that we can manipulate within the hook functions. Let’s take a look at the hook functions it provides:

  • Bind: called only once, when a directive is first bound to an element, where one-time initialization can be performed.
  • Inserted: Called when the bound element is inserted into the parent node (only ensures that the parent exists, but not necessarily that it has been inserted into the document).
  • Update: called when the component’s VNode is updated, but may occur before its children are updated. The value of the directive may or may not have changed, but you can ignore unnecessary template updates by comparing the values before and after the update (see below for the detailed hook function arguments).
  • ComponentUpdated: component VNode directive and its children VNode all updated call.
  • Unbind: called only once, when a directive is unbound from an element.

All of the above methods take four parameters, as follows.

  • El: The element bound by the directive, which can be used to manipulate the DOM directly.
  • Binding: An object containing the following properties:
  • Name: indicates the directive name, excluding the V – prefix.
  • Value: specifies the binding value of the directive. For example, if v-my-directive=”1 + 1″, the binding value is 2.
  • OldValue: The previous value of the instruction binding, available only in update and componentUpdated hooks, regardless of whether the value has changed.
  • Expression: indicates a string directive expression. For example, in v-my-directive=”1 + 1″, the expression is “1 + 1”.
  • Arg: Parameter passed to the directive. This parameter is optional. For example, in v-my-directive:foo, the parameter is “foo”.
  • Modifiers: An object that contains a modifier, such as {foo: true, bar: true} in v-my-directive.foo.bar.
  • Vnode: virtual node generated by Vue compilation.
  • OldVnode: The last virtual node, available only in update and componentUpdated hooks.

All parameters except EL should be read-only and should not be modified. If you need to share data between hooks, it is recommended to do so through the element’s dataset.

Reference: vUE official website custom directive

nextTick

Functional description

Perform a delayed callback after the next DOM update loop ends. Use this method immediately after modifying the data to get the updated DOM.

The official website is always so official, let’s explain it in plain English:

If there are some methods that need to be executed after the DOM is rendered, then you can listen on nextTick to get the DOM after the DOM is rerendered. Technically, nextTick is the callback method for DOM rendering!

use

There are two ways to use nextTick:

  1. Vue.nextTick( [callback, context] )
  2. vm.$nextTick( [callback] )

The only difference between these two approaches is: NextTick ([callback, context]) this defaults to window (we can also change the default based on its second argument). $nextTick([callback]) this defaults to the instance (VM) that called it.

Application scenarios

Now we have a

tag that holds a description that we need to get

After showing the height of the description information, you can implement this requirement with nextTick.

let $this = this;
setTimeout(() = > {
    $this.msg = 'Here's our descriptive information, it's long, it's long, it's long, it's long, it's long, it's long, it's long, it's long, it's long, it's long, it's long, it's long.';
    // We can also use Vue's ref to get the DOM
    var msgDom = document.getElementById('msg');

    $this.$nextTick(function() {
        console.log('MSG has a height of:' + msgDom.offsetHeight);
    });
}, 1000);
Copy the code

We use nextTick to listen to the callback method after the DOM has been rendered. At this time, the msgDom obtained is the height of the DOM after the rerendered.

Use as a Promise (added since 2.1.0, see next tip)

Vue.nextTick()
  .then(function () {
    // The DOM is updated
  })
Copy the code

New since 2.1.0: Return a Promise if no callback is provided and in a promise-supporting environment. Please note that Vue does not come with a Promise polyfill, so if your target browser does not support Promises natively, you will have to provide your own polyfill.

These are the most commonly used VUE apis, if you are interested in learning more, please refer to the official VUE API document provided at the beginning!

Thank you for reading, if it helps you, welcome to the “CRMEB” nugget. Code cloud has our open source mall project, knowledge paid project, JAVA edition full open source mall system, learning and research welcome to use, old Iron easy point star bai, the boss reward five cents, cent you two cents, 😂😂 pay attention to keep in touch with us!