Vue Chapter One-Custom Instructions

Preface

In the previous article, I introduced the use of some instructions in Vue. According to the official statement, in Vue2.0, the main form of code reuse and abstraction is components. However, in some cases, ordinary DOM elements are still needed. For low-level operations, custom instructions are needed at this time.

Global directive

Now we have to do such an instruction: when the page is loaded, the text box will automatically focus.
Examples are as follows:

<body>

<input type="text" v-focus>

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script type="text/javascript">
    // 注册一个全局自定义指令 `v-focus`
    Vue.directive('focus', {
     
     
        // 当被绑定的元素插入到 DOM 中时……
        inserted: function (el) {
     
     
            // 聚焦元素
            el.focus()
        }
    })
</script>
</body>

It is used here to create Vue.directivea global command. There are two parameters, one is the name of the command, and the other is an object, which is used to implement the specific method of logic. Of course, some hook functions will be used, which will be mentioned below.

Local instruction

<body>
    <div id="app">
        <input type="text" v-focus>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script type="text/javascript">
        var app = new Vue({
     
     
            el: '#app',
            data:{
     
     
                message:"message"
            },
            directives: {
     
     
                focus: {
     
     
                    // 指令的定义
                    inserted: function (el) {
     
     
                        el.focus()
                    }
                }
            }
        })
    
    </script>
</body>

The creation of a local instruction is basically the same as the creation of a global instruction. The difference is that in the local Vue object, a directivesrepresentative can declare multiple instructions here. Of course, this instruction can only take effect within "#app"the tag.
If you understand both the global and local instructions, then other functions (global and local) are all at your fingertips. They are all a routine.

Hook function

The hook function is mentioned above. An instruction definition object can provide the following hook functions (all optional):

  • bind: Only called once, called when the instruction is bound to the element for the first time. One-time initialization settings can be performed here

  • inserted: Called when the bound element is inserted into the parent node (only the parent node is guaranteed to exist, but not necessarily inserted into the document)

  • update: Called when the VNode of the component is updated, but it may happen before its child VNode is updated. The value of the instruction may or may not have changed. But you can ignore unnecessary template updates by comparing the values ​​before and after the update

  • componentUpdated: Called after the VNode of the component where the instruction is located and its sub-VNodes are all updated

  • unbind: Only called once, called when the instruction and element are
    unbound. Next, let’s look at the parameters of the hook function (ie el, binding, vnode and oldVnode)

parameter

The instruction hook function will be passed the following parameters:

  • el: The element bound by the instruction can be used to directly manipulate the DOM
  • binding: An object containing the following properties:
    • name: Command name, excluding v- prefix
    • value: The bound value of the instruction, for example: v-my-directive="1 + 1", the bound value is 2
    • oldValue: The previous value bound by the instruction, only available in the update and componentUpdated hooks. Available regardless of value change
    • expression: Command expression in string form. For example, in v-my-directive="1 + 1", the expression is "1 + 1"
    • arg: Parameters passed to the instruction, optional. For example, in v-my-directive:foo, the parameter is "foo"
    • modifiers: An object containing modifiers. For example: in v-my-directive.foo.bar, the modifier object is {foo: true, bar: true}
  • vnode: Virtual node generated by Vue compilation
  • oldVnode: The last virtual node, only available in the update and componentUpdated hooks

Except for el, other parameters should be read-only and should not be modified. If you need to share data between hooks, it is recommended to use the dataset of the element.

Examples are as follows:

<body>
    <div id="hook-arguments-example" v-demo:foo.a.b="message"></div>

    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script type="text/javascript">
        Vue.directive('demo', {
     
     
            bind: function (el, binding, vnode) {
     
     
                var s = JSON.stringify
                el.innerHTML =
                    'name: '       + s(binding.name) + '<br>' +
                    'value: '      + s(binding.value) + '<br>' +
                    'expression: ' + s(binding.expression) + '<br>' +
                    'argument: '   + s(binding.arg) + '<br>' +
                    'modifiers: '  + s(binding.modifiers) + '<br>' +
                    'vnode keys: ' + Object.keys(vnode).join(', ')
            }
        })

        new Vue({
     
     
            el: '#hook-arguments-example',
            data: {
     
     
                message: 'hello!'
            }
        })
    </script>
</body>

The rendering results are as follows

name: "demo"
value: "hello!"
expression: "message"
argument: "foo"
modifiers: {
    
    "a":true,"b":true}
vnode keys: tag, data, children, text, elm, ns, context, fnContext, fnOptions, fnScopeId, key,
componentOptions, componentInstance, parent, raw, isStatic, isRootInsert, isComment, isCloned,
isOnce, asyncFactory, asyncMeta, isAsyncPlaceholder

Trigger the same behavior when bind and update, without caring about other hooks, which can be abbreviated as follows:

Vue.directive('color-swatch', function (el, binding) {
    
    
  el.style.backgroundColor = binding.value
})

In the process of customizing instructions, the role of the hook function is very important, because it determines whether your instructions will mount successfully.

Guess you like

Origin blog.csdn.net/qq_44091773/article/details/112637465