美文网首页
Vue中指令的使用小结以及示例

Vue中指令的使用小结以及示例

作者: 周星星的学习笔记 | 来源:发表于2022-08-30 20:56 被阅读0次

指令相当于Vue中的一个个的命令,这些命令内部包含一些功能集合,诸如:v-if、v-model 等等,Vue允许我们可以自定义指令,下面就以一个示例简单总结一下自定义指令定义与使用。

一、定义指令的方式

1.指令的定义(以v-开头)

//会实例化一个指令,该指令没有参数 
`v-xxx`
  
//将值传到指令中,value通常是一个定义的变量
`v-xxx="value"`  
  
//将字符串传入到指令中,需要加单引号
`v-xxx="'string'"` 
  
//传参数(`arg`)
`v-xxx:arg="value"` 
  
//使用修饰符(`modifier`)
`v-xxx:arg.modifier="value"` 

2.指令的钩子函数

bind:只调用一次,指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置
inserted:被绑定元素插入父节点时调用 (仅保证父节点存在,但不一定已被插入文档中)
update:所在组件的 VNode 更新时调用,但是可能发生在其子 VNode更新之前。指令的值可能发生了改变,也可能没有。但是你可以通过比较更新前后的值来忽略不必要的模板更新
componentUpdated:指令所在组件的 VNode 及其子 VNode 全部更新后调用
unbind:只调用一次,指令与元素解绑时调用

3.所有的钩子函数都包含以下两个参数

el:指令所绑定的元素,可以用来直接操作 DOM
binding:数据对象,包含以下的一些节点

`name`:指令名,不包括 v- 前缀。
`value`:指令的绑定值,例如:v-my-directive="1 + 1" 中,绑定值为 2。
`oldValue`:指令绑定的前一个值,仅在 update 和 componentUpdated 钩子中可用。无论值是否改变都可用。
`expression`:字符串形式的指令表达式。例如 v-my-directive="1 + 1" 中,表达式为 "1 + 1"。
`arg`:传给指令的参数,可选。例如 v-my-directive:foo 中,参数为 "foo"。
`modifiers`:一个包含修饰符的对象。例如:v-my-directive.foo.bar 中,修饰符对象为 { foo: true, bar: true }
`vnode`:Vue 编译生成的虚拟节点
`oldVnode`:上一个虚拟节点,仅在 update 和 componentUpdated 钩子中可用

4.指令的注册

  • 局部注册
//导入指令文件
import myChange from './directives/my-change'

export default {
  directives: {
    myChange
  }
}
</script>
  • 全局注册
//在 main.js 中注册
// 例如:输入框聚焦
Vue.directive("focus", {
  inserted: function (el) {
    // 聚焦元素
    el.focus();
  },

二、示例(点击按钮切换颜色)

1.新建一个指令逻辑处理文件(src/directives/my-change.js)

export default {
  bind(el, bindings) {
    console.log('bind:el:', el)
    console.log('bind:bindings:', bindings)
  },
  update(el, bindings) {
    console.log('update:bind:el:', el)
    console.log('update:bind:bindings:', bindings)
    if (bindings.value == 'hello') {
      //修改当前按钮背景色
      el.style.background = 'red'
    } else {
      //修改当前按钮背景色
      el.style.background = 'green'
    }
  }
}

2.使用指令

<template>
  <div id="app">
    <my-button btn-style="btn-success" v-my-change="mark">成功</my-button>
    <button @click="changeText">切换</button>
  </div>
</template>

<script>
import myChange from './directives/my-change'

export default {
  directives: {
    myChange
  },
  data() {
    return {
      mark: 'admin'
    }
  },
  methods: {
    changeText() {
      this.mark = this.mark == 'admin' ? 'hello' : 'admin'
    }
  }
}
</script>

<style></style>

3.效果

切换前
切换后

三、参考

vue中自定义指令directive的详细指南

相关文章

网友评论

      本文标题:Vue中指令的使用小结以及示例

      本文链接:https://www.haomeiwen.com/subject/tiqrnrtx.html