vue how custom global / private key modifier, filtered and instruction

A, vue custom global modifier keys?

In front of a learning event modifier, then what is the key modifier?

When listening keyboard events, we often need to check detailed button. Vue allowed to v-onadd modifier keys when the monitor keyboard events:

<input v-on:keyup.enter="submit">

Only when keyboard keys press Enter (Enter) key, it will trigger a call submit () method.

You can also go directly to KeyboardEvent.keyany valid key name exposure into a kebab-case as a modifier:

<input v-on:keyup.page-down="onPageDown">

In the above example, the processing function will only $event.keyequal PageDownis invoked.

 

Then look at the key code

keyCode The event usage has been deprecated and may not be supported by the latest browsers.

Use keyCode attribute is allowed:

<input v-on:keyup.13="submit">

In order to support older browsers, if necessary, Vue offers alias vast majority of commonly used keys code:

.enter
.tab
.delete (捕获“删除”和“退格”键)
.esc
.space
.up
.down
.left
.right

 There are some key ( .escand all of the arrow keys) have different in IE9 in keyvalue, if you want to support IE9, these built-in aliases should be preferred.

If the above are not commonly used keys you want, if you want to customize the modifier keys alias how to do it?

Key code values ​​113 where f2 is the key corresponding to

// 自定义全局按键修饰符
Vue.config.keyCodes.f2 = 113

When used:

<input type="text" v-model="name" @keyup.f2="add">

Common keyboard keys corresponding to the key code value can refer to this link Encyclopedia: https://www.cnblogs.com/wuhua1/p/6686237.html


1.x custom keyboard modifiers [to understand]

Vue.directive('on').keyCodes.f2 = 113;

2.x custom keyboard modifiers

  •  By `Vue.config.keyCodes key name = value 'from the case of modifier defined alias:

Vue.config.keyCodes.f2 = 113;
  • Using a custom key modifier:
<input type="text" v-model="name" @keyup.f2="add">

 

 

Second, custom global filter

The so-called global filters, is that all VM instances are shared.

Vue.filter('myFilter', function (data) {
    return data + '123'
}) 

 How to call?

<h3>{{ dt | myFilter}}</h3>
// data 中 dt: new Date()

Filter format when calling {{name | filter name}}, wherein | symbols, we referred to pipe character

// 过滤器的定义语法
// Vue.filter('过滤器的名称', function(){})

// 过滤器中的 function ,第一个参数,已经被规定死了,永远都是 过滤器 管道符前面 传递过来的数据
/* 
    Vue.filter('过滤器的名称', function (参数) {
          return 要做的操作
    }) 
*/

Filter function can set the default parameter values, the default is the null value pattern where

Vue.filter('dateFormat', function (dateStr, pattern = "") {
      // do something ...
})

 

Third, define private filters

 With the Global Filters, of course, there may be private (local) filter, is a so-called private can only be used in the region of the current VM object View control

// 如何自定义一个私有的过滤器(局部)
    var vm2 = new Vue({

      el: '#app2',
      data: {},
      methods: {},
      filters: {
        dateFormat: function (data) {
            return data + '123'
        }
      }

    })

 Private filter filters only need to define a field, which is provided in the filter name is defined and the method can.

So when the global and local filters and filters exist with the same name, when the call is called global or local filter it?

A: When there are two local and global same name filters when will the principle of proximity call, namely: local filter precedence over global filter is called!

 

Fourth, the global instruction Custom

I learned a lot about the previous instructions of vue: v-cloak, v-text, v-html, v-on, v-bind, v-for, v-if, v-show, v-model, etc.

There are no instructions are found in vue beginning to v-

So there is a Vue all the instructions agreed that, when called, are beginning to v-

To define a global directive when we need to use   Vue.directive ()

among them:

  • Parameter 1: command name, note, when defined, in front of the name of the command, the prefix does not require additional v-, (but in the time of the call, must be added v- prefix before the call instruction name)
  • Parameter 2: is an object that the body, there are some instructions related functions, these functions may be particular stage, while executing the operation

 Suppose we enter a page, to make an input text box has focus, usually js Our operations are:

document.getElementById('search').focus()

But vue, we can automatically get the focus of a custom command to achieve

First on the code:

Vue.directive('focus', {
      bind: function (el) { 

      },
      inserted: function (el) {  
        el.focus()
      },
      updated: function (el) {  

      }
})

You can not read the code? So here we must look at the hook function  this thing (refer vue official website tutorial)

A command definition object may provide several hook function (all optional):

  • bind: Only called once, the first time is bound to the command element of the call. Here you can set a one-time initialization.

  • inserted: It is called when the binding element into the parent node (only ensure that there is a parent node, but does not necessarily have to be inserted in the document).

  • update: When VNode update where the assembly calls, but may occur before their children VNode update . The value of the instruction may be changed, or may not. But you can ignore unnecessary template update by comparing the values before and after the update (hook function parameters detailed below).

  • componentUpdated: Command where components VNode its sub VNode all calls after the update.

  • unbind: Only called once, when the call instruction and tie element solution.

Next we look at the parameters of the hook function (ie el, binding, vnodeand oldVnode).


Hook function parameters

Instruction hook function will be passed the following parameters:

  • el: Elements bound instruction can be used to directly operate DOM.
  • binding: An object that contains the following properties:
    • name: Command name, not the v-prefix.
    • value: Binding command value, for example: v-my-directive="1 + 1", the binding value 2.
    • oldValue: Previous value of command binding, only in updateand componentUpdatedavailable hooks. Regardless of whether the value change are available.
    • expression: Instruction string expression. For example v-my-directive="1 + 1", the expression is "1 + 1".
    • arg: Pass the command parameters, optional. For example v-my-directive:foo, the parameters "foo".
    • modifiers: An object that contains modifier. For example: v-my-directive.foo.bar, the modifier object { foo: true, bar: true }.
  • vnode: Vue compiler-generated virtual node. Venue VNode API for more details.
  • oldVnode: A virtual node only updateand componentUpdatedavailable hooks.

Apart eladdition, other parameters should be read-only, not to be modified. If you need to share data between the hook, we recommended by the elements to carry out.dataset


Back to the code, why el.focus () on the inserted function?

  • Whenever instruction bound to the elements, the implementation of this bind function will immediately be executed only once. In the last element binding instructions when not inserted into the DOM to go, this time, call the focus method does not work

  • One element, only after inserting the DOM, in order to gain focus (inserted representation element into the DOM when the trigger is executed inserted function [1])

  • JS behavior and related operations, it is best to perform inserted in

 

Custom font color of a set of instructions, how to do?

Vue.directive('color', {
     
      bind: function (el, binding) {

        // el.style.color = 'red'
        console.log(binding.name)
        console.log(binding.value)
        console.log(binding.expression)

        el.style.color = binding.value
      }

})

transfer:

<h3 v-color="'green'">哈哈</h3>

What are the console output to see:

So here's why the color is set in a bind function written in it? 

  • Style, as long as the binding to the elements through instruction, whether this element has not been inserted into the page to go, this element certainly has an inline style

  • The future will certainly display elements to the page, this time, the browser's rendering engine is bound to parse style, apply to this element

  • And style-related operations, generally can be performed in bind

 

V. custom private instruction

And similar to the definition of private filters, but also add a field, which is the  directives

var vm2 = new Vue({
      el: '#app2',
      data: {},
      methods: {},
      directives: { // 自定义私有指令
        'fontweight': { // 设置字体粗细的
          bind: function (el, binding) {
            el.style.fontWeight = binding.value
          }
        },
        'fontsize': function (el, binding) { // 注意:这个 function 等同于 把 代码写到了 bind 和 update 中去
          el.style.fontSize = parseInt(binding.value) + 'px'
        }
      }
    })

Note the use of two different wording 

Call time:

<h3 v-color="'pink'" v-fontweight="900" v-fontsize="50">哈哈</h3>

 About priority and filters of the same name in the same call, the principle of proximity.

 

 

 

发布了7 篇原创文章 · 获赞 4 · 访问量 556

Guess you like

Origin blog.csdn.net/control_ling/article/details/104441779