Learn the Web from scratch Vue.js (ii) filter, key modifier, custom directive

Source: Internet
Author: User
Tags getdate modifier custom name

Hello everyone, here is "learn the Web series from scratch" and synchronize updates at the following address ...

  • Github:github.com/daotin/web
  • Public number: The top of the Web front
  • Blog Park: http://www.cnblogs.com/lvonve/
  • csdn:blog.csdn.net/lvonve/

Here I will start with the Web front End 0 Foundation, step-up learning web-related knowledge points, during the period will also share some fun projects. Now let's go to the Web Front end learning Adventure tour!

First, brand management case

Such as

1, after implementing the input ID and name, click the Add button to add to the table;

2, click on the Data del, you can delete this data.

Code:

<!     DOCTYPE html>

Attention:

1, the event name can be appended with parentheses ( @click="addClick" equivalent to @click="addClick() , so write, you can pass the argument.) )

1. Increase search Demand

Enter a string in query, which is displayed if the name item includes a string in query.

Analysis:

If you want to meet the criteria to display the related rows, then the list <tr v-for="item in list"> in the list is a variable. Here we use a function that determines whether the string in the query is included, and then copies the contained copy into the new array, populating the list with the position:

<tr v-for="item in search(keywords)">

methods: {                addClick() {                  //...                },                delClick(id) {                  //...                },                // 添加的用于判断的函数                search(keywords) {                    // 定义新数组保存符合条件的项                    let newList = [];                    this.list.forEach((item, index) => {                        // 包含则返回true                        if (item.name.includes(keywords)) {                            newList.push(item);                        }                    });                    return newList;                }            }
Second, filter

Vue allows custom filters that can be used as some common text formatting.

Filters can only be used in two places: an interpolation expression and v-bind an expression .

1. Global Filter

Basic usage:

<body>    <div id="box">        <p>{{msg | msgFormat}}</p>    </div>    <script>        // 使用Vue.filter来定义一个过滤器:        // 第一个参数:过滤器函数名称        // 第二个参数:过滤器函数体        // 过滤器的参数就是管道符的前面待处理的字符串。        Vue.filter('msgFormat', (data) => {            return data.replace("vue", "Daotin");        });        var vm = new Vue({            el: " #box ",            data: {                msg: "hello vue"            },            methods: {}        });    </script></body>

1, the use of Vue.filter (); To define a filter.

2, the first parameter: Filter function name; second parameter: Filter function body

3. The filter parameter is the string to be processed before the pipe character .

The filter function in an interpolation expression can take parameters:

Accordingly, the parameters of Msgformat in Vue.filter (' Msgformat ', (data, arg1,arg2,...) are placed from the second position.

Can take more than one parameter.

<body>    <div id="box">        <p>{{msg | msgFormat('is a boy', 'and good')}}</p>    </div>    <script>        // 使用Vue.filter来定义一个过滤器:        // 第一个参数:过滤器函数名称        // 第二个参数:过滤器函数体        // 过滤器的参数就是管道符的前面待处理的字符串。        Vue.filter('msgFormat', (data, arg1, arg2) => {            return data.replace("vue", "Daotin " + arg1 + arg2);        });        var vm = new Vue({            el: " #box ",            data: {                msg: "hello vue"            },            methods: {}        });    </script></body>

Use global filters to format the CTime of the brand management case:

<td>{{item.ctime | ctimeFormat}}</td>...// ctime 过滤器Vue.filter('ctimeFormat', (data) => {  let time = new Date(data);  let year = time.getFullYear();  let month = time.getMonth() + 1;  let day = time.getDate();  let hour = time.getHours();  let minute = time.getMinutes();  return `${year}-${month}-${day} ${hour}:${minute}`;});
2. Private filter

A global filter is one in which all VM instances can be used if there are multiple VM instances.

The global filter is written under the script direct tag.

And the private filter is written in the VM object:

Note: The invocation principle of the filter is the nearest principle , which is to call the private filter before calling the global filter.

Padstart and Padend

// ctime 过滤器Vue.filter('ctimeFormat', (data) => {    let time = new Date(data);    let year = time.getFullYear();    let month = (time.getMonth() + 1).toString().padStart(2, '0');    let day = (time.getDate()).toString().padStart(2, '0');    let hour = (time.getHours()).toString().padStart(2, '0');    let minute = (time.getMinutes()).toString().padStart(2, '0');    let second = (time.getSeconds()).toString().padStart(2, '0');    return `${year}-${month}-${day} ${hour}:${minute}:${second}`;});

Use the string new method in ES6 String.prototype.padStart(maxLength, fillString='') or String.prototype.padEnd(maxLength, fillString='') to populate the string;

Padstart: Filling from the beginning

Padend: padding from the end

MaxLength: Maximum length after filling

Fillstring: The string to be populated (fillstring= ", not filled with empty characters)

Three, key modifier

We now have a need to enter the ID and name and not click on the Add button, but press ENTER will also need to add to the list.

We can add a button to lift the event in the Name input box and specify that it is triggered when the ENTER key is lifted.

<label for="name">  name:  <input type="text" id="name" v-model="name" @keyup.enter="addClick">

.enter: Is the key modifier.

The key modifiers provided by the system are:

    • .enter
    • .tab
    • .delete(Capture "Delete" and "backspace" keys)
    • .esc
    • .space
    • .up
    • .down
    • .left
    • .right

What if we want to customize the other keys?

Vue.config.keyCodes.f2 = 113;you can add F2 as a key modifier to the system key modifier.

What is the specific value of each key? The following are the common key codes.

KeyCode 8 = BackSpace Backspacekeycode 9 = Tab Tabkeycode = Clearkeycode = Enterkeycode = Shift_lkeycode + = Con Trol_lkeycode = Alt_lkeycode = Pausekeycode = Caps_lockkeycode = Escape Escapekeycode + = Spacekeycode = P Riorkeycode = Nextkeycode = Endkeycode = Homekeycode PNs = Leftkeycode = Upkeycode = Rightkeycode = Downk Eycode = Selectkeycode = Printkeycode = Executekeycode = Insertkeycode = Deletekeycode 48 = Helpkeycode = 0 Equal Bracerightkeycode = 1 Exclam onesuperiorkeycode = 2 Quotedbl twosuperiorkeycode Wuyi = 3 section Threesuperi Orkeycode = 4 Dollarkeycode = 5 Percentkeycode = 6 Ampersandkeycode = 7 Slash Braceleftkeycode 8 Parenlef  T Bracketleftkeycode = 9 Parenright Bracketrightkeycode = a Akeycode (= b bkeycode) = c Ckeycode = d Dkeycode Eurosignkeycode = e E = f Fkeycode = g Gkeycode = h Hkeycode = i ikeycode = J Jkeycode = k Kkeycode Lkeycode = L = m m Mukeycode = n Nkeycode = o okeycode = p Pkeycode bayi = q Q atkeycode = R Rkeycode = s Skeycode = t TKEYC Ode = u Ukeycode = v Vkeycode xkeycode = w wkeycode (x ykeycode) = y Zkeycode = z kp_0  Kp_1 = Kp_1keycode 98 = kp_2 Kp_2keycode = kp_3 Kp_3keycode = kp_4 Kp_4keycode 101 = kp_5 Kp_5keycode 102 = KP_6  Kp_6keycode 103 = kp_7 Kp_7keycode 104 = kp_8 Kp_8keycode = kp_9 Kp_9keycode 106 = kp_multiply KP_MultiplykeyCode 107 = Kp_add Kp_addkeycode 108 = kp_separator Kp_separatorkeycode 109 = kp_subtract Kp_subtractkeycode = KP_Decimal KP_De Cimalkeycode 111 = kp_divide Kp_dividekeycode, f1keycode 113 = F2keycode = F3keycode, = F4keycode = F5keyC  Ode 117 = F6keycode 118 = F7keycode 119 = F8keycode = F9keycode 121 = F10keycode 122 = F11keycode 123 = F12keycode 124 = F13keycode = F14keycode 126 = F15keycode 127 = F16keycode = F17keycode 129 = F18keycode = F19keycode 131 = F20keycode = F21KEYCOde 133 = F22keycode 134 = F23keycode 135 = F24 

Example:

<input type="text" id="name" v-model="name" @keyup.f2="addClick">   //...  <script>    Vue.config.keyCodes.f2 = 113;</script>
Iv. Custom Directives

In addition to the core functionality of the default built-in directives ( v-model etc.), Vue also allows the registration of custom directives. Custom directives are instructions that v- begin with.

For example, we want the brand management case to get the focus of the query input box as soon as it enters the page, but Vue does not provide such an instruction.

Before we could get the focus by getting DOM elements and then using DOM元素.focus(); methods. But the way to get DOM elements is not recommended in Vue. At this point we can use the custom instructions to achieve the focus.

For example: We want to define a v-focus command to get the focus.

<label for="sel">  Query:  <input type="text" id="sel" v-model="keywords" v-focus></label><script>    // 自定义全局指令 v-focus,为绑定的元素自动获取焦点:        Vue.directive('focus', {            inserted: function (el) { // inserted 表示被绑定元素插入父节点时调用                el.focus();            }        });</script>

1, the definition of custom directives, do not need to add v- , when using the need to add.

2, note: In each function, the first parameter, always, represents the element that is bound to the el instruction, the El parameter, is a native JS object.

3, and JS behavior-related operations, preferably in the inserted implementation

1. Hook function

Inserted is a hook function, there are several similar hooks, but the application scenario is different:

    • inserted: Called once when a bound element is inserted into a DOM element (when rendered to a page from memory if the inserted is bound to execute ).
    • bind: Called only once, when the instruction is first bound to an element. A one-time initialization setting can be performed here (when the code is loaded into memory, if bind is bound to execute , such as the setting of the styling style, bind with BIND).
    • update: Called when the component's Vnode is updated, but may occur before its child Vnode update . The value of the instruction may or may not have changed.

Summary: General:

1, the operation related to JS behavior is executed in inserted;

2, the style is related to the execution in bind.

2. Hook function parameters

The command hook function is passed in the following parameters:

    • el: the element that the directive binds to, which can be used to manipulate the DOM directly.
    • binding: An object that contains the following properties:
      • name: instruction name, not including v- prefix.
      • value: The binding value of the directive, for example: v-my-directive="1 + 1" in, the binding value is 2 .
      • expression: An instruction expression in the form of a string. For example v-my-directive="1 + 1" , the expression is "1 + 1" .
      • ...
    • ...

We can assign values to custom directives, for example, we want to assign values to the font color of the query text box:

<label for="sel">  Query:  <input type="text" id="sel" v-model="keywords" v-focus v-color="'red'"></label>

It is used v-color="'red'" , not v-color="red" , because if it is a red string, it looks like a variable in Vue's data, and here is the string red.

Custom V-color directives:

Vue.directive("color", {  bind(el, binding) {    el.style.color = binding.value;  }});

Binding: This name can be arbitrary.

3. Custom Private Instructions

A custom private directive is the addition of an attribute to a VM instance, which directives is an object where the property is the name of the custom directive (without V), and the value is an object, which is a list of hook functions.

var vm = new Vue({  el: "#app",  data: {    //...  },  methods: {    //...  },  directives: {    "color": {      bind(el, binding) {        el.style.color = binding.value;      }    }  }});
4. Shorthand for custom directives

We have previously followed an object with the name of the custom directive, with a list of bind,inserted,update hooks.

Now, you don't need to keep up with an object:

directives: {  "color": (el, binding) => {    el.style.color = binding.value;  }}

The custom name can be followed directly by an anonymous function, which is equivalent to the set of hook functions for bind and update. So, if you only need to set the element in bind or update, you can use this shorthand method, of course, if it is inserted, it is the way to write back the object.

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.