1.2 自定义指令v-xxx绑定

1.2.1 v-xxx函数绑定

1.2.2 v-xxx格式绑定

1.2.3 例子监听元素尺寸改变

1.2.4 高级例子

  1. <template>
  2. <div>
  3. <!-- 1.2.1/1.2.3 -->
  4. <el-card v-size="cardResize">
  5. <p>内容1</p>
  6. <p>内容2</p>
  7. <p>内容3</p>
  8. <p>内容4</p>
  9. </el-card>
  10. <!-- 1.2.2 -->
  11. <div>
  12. <p v-lower-text="innerText"></p>
  13. </div>
  14. </div>
  15. </template>
  16. <script>
  17. export default {
  18. //局部指令,只在当前Vue中才有效
  19. directives: {
  20. // 1.2.1/1.2.3 使用局部注册指令的方式
  21. resize: {
  22. // 指令的名称
  23. bind(el, binding) {
  24. // el为绑定的元素,binding为绑定给指令的对象
  25. let width = '',
  26. height = ''
  27. function isReize() {
  28. const style = document.defaultView.getComputedStyle(el)
  29. if (width !== style.width || height !== style.height) {
  30. binding.value({ with: style.width, height: style.height }) // 关键
  31. }
  32. width = style.width
  33. height = style.height
  34. }
  35. el.__vueSetInterval__ = setInterval(isReize, 300)
  36. },
  37. unbind(el) {
  38. clearInterval(el.__vueSetInterval__)
  39. },
  40. },
  41. // 1.2.2 将内容转为小写
  42. "lower-text" : function(el, binding){
  43. el.textContent = binding.value.toLowerCase();
  44. }
  45. },
  46. data() {
  47. return {
  48. // 1.2.2
  49. innerText: 'Never Give Up!(innerText)'
  50. }
  51. },
  52. watch: {
  53. },
  54. created() {
  55. },
  56. mounted() {
  57. // 1.2.1/1.2.3
  58. cardResize(size) {
  59. console.log(size)
  60. },
  61. },
  62. methods: {
  63. }
  64. }
  65. </script>
  66. <style lang="scss" scoped>
  67. </style>

1.2.5 全局注册

  1. <script>
  2. //自定义全局指令
  3. //el:指令属性所在的html标签对象
  4. //binding:包含指令相关信息数据的对象
  5. Vue.directive("upper-text", function(el, binding){
  6. console.log(el);
  7. console.log(binding);
  8. el.textContent = binding.value.toUpperCase();
  9. });
  10. </script>