Home > Web Front-end > JS Tutorial > body text

Vue.js custom directive method

一个新手
Release: 2017-09-25 10:06:41
Original
1569 people have browsed it
  • In addition to the default core directives (v-model and v-show), Vue also allows the registration of custom directives.

  • Register a global directive v-focus. The function of this directive is to focus the element when the page is loaded.

<p id="app">
    <p>页面载入时,input 元素自动获取焦点:</p>
    <input v-focus></p><script>// 注册一个全局自定义指令 v-focusVue.directive(&#39;focus&#39;, {  // 当绑定元素插入到 DOM 中。
  inserted: function (el) {
    // 聚焦元素
    el.focus()
  }
})// 创建根实例var a = new Vue({
  el: &#39;#app&#39;})</script>
Copy after login
  • You can also use the directives option in the instance to register local instructions, so that the instructions can only be used in this instance

<p id="app">
  <p>页面载入时,input 元素自动获取焦点:</p>
  <input v-focus></p><script>// 创建根实例new Vue({
  el: &#39;#app&#39;,
  directives: {    // 注册一个局部的自定义指令 v-focus
    focus: {      // 指令的定义
      inserted: function (el) {
        // 聚焦元素
        el.focus()
      }
    }
  }
})</script>
Copy after login
  • The directive definition function provides several hooks Function (optional)

bind: 只调用一次,指令第一次绑定到元素时调用,用这个钩子函数可以定义一个在绑定时执行一次的初始化动作。
inserted: 被绑定元素插入父节点时调用(父节点存在即可调用,不必存在于 document 中)。
update: 被绑定元素所在的模板更新时调用,而不论绑定值是否变化。通过比较更新前后的绑定值,可以忽略不必要的模板更新(详细的钩子函数参数见下)。
componentUpdated: 被绑定元素所在模板完成一次更新周期时调用。
unbind: 只调用一次, 指令与元素解绑时调用。
Copy after login
  • Hook function parameters

钩子函数的参数有:
el: 指令所绑定的元素,可以用来直接操作DOM 。
binding: 一个对象,包含以下属性:
name: 指令名,不包括 v- 前缀。
value: 指令的绑定值, 例如: v-my-directive="1 + 1", value 的值是 2。
oldValue: 指令绑定的前一个值,仅在 update 和 componentUpdated 钩子中可用。无论值是否改变都可用。
expression: 绑定值的字符串形式。 例如 v-my-directive="1 + 1" , 
expression 的值是 "1 + 1"。
arg: 传给指令的参数。例如 v-my-directive:foo, arg 的值是 "foo"。
modifiers: 一个包含修饰符的对象。 例如: v-my-directive.foo.bar, 修饰符对象 modifiers 的值是 { foo: true, bar: true }。
vnode: Vue 编译生成的虚拟节点,查阅 VNode API 了解更多详情。
oldVnode: 上一个虚拟节点,仅在 update 和 componentUpdated 钩子中可用。
Copy after login

The above is the detailed content of Vue.js custom directive method. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!