Vue 进阶构造属性

55 阅读1分钟

Directive 指令

自定义指令

  • 内置指令:v-ifv-forv-showv-html

  • 学习然如何自己造一个指令:造出v-x,点击即出现一个x

两种写法

一、声明一个全局指令

Vue.directive('x', directiveOptions),可以在任何组件里用v-x了。

  • main.js
import Vue from "vue";
import App from "./App.vue";

Vue.config.productionTip = false;

Vue.directive('y', {
  inserted(el){
    el.addEventListener('click', ()=>{
      console.log('y')
    })
  }
})
new Vue({
  template: `
    <div v-y>hello</div>
  `
}).$mount("#app");

二、声明一个局部指令

new Vue({
  ...
  directives: {
    "x": directiveOptions
  }
})
  • v-x 只能用在该实例中,不能运用到其他实例中

directiveOptions

五个函数属性

  • bind(el, info, vnode, oldVnode) ——类似created

只调用一次,指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置。

  • inserted(el, info, vnode, oldVnode) ——类似mounted

被绑定元素插入父节点时调用 (仅保证父节点存在,但不一定已被插入文档中)。

  • updated(el, info, vnode, oldVnode) ——类似updated

所在组件的 VNode 更新时调用,但是可能发生在其子 VNode 更新之前。指令的值可能发生了改变,也可能没有。但是你可以通过比较更新前后的值来忽略不必要的模板更新 (详细的钩子函数参数见下)。

  • component Update(el, info, vnode, oldVnode) ——用的不多

指令所在组件的 VNode 及其子 VNode 全部更新后调用。

  • unbind(el, info, vnode, oldVnode) ——类似destroyed

只调用一次,指令与元素解绑时调用。

image.png

import Vue from "vue/dist/vue.js"; // 故意使用完整版
import App from "./App.vue";
Vue.config.productionTip = false;
  new Vue({
    directives: {
      on2: {
     // bind 可以改为 inserted
        bind(el, info) {
          el.addEventListener(info.arg, info.value);
         // Vue 自带的 v-on 并不是这样实现的,它更复杂,用了事件委托
        },
        unbind(el, info) {
          el.removeEventListener(info.arg, info.value);
       }
    }
},
template: `
  <button v-on2:click="hi">点我</button>
`,
  methods: {
    hi() {
      console.log("hi");
    }
  }
}).$mount("#app");

缩写

  • directiveOptions在某些条件下可以缩写为函数,用的不多

image.png

指令的作用:

主要是为减少重复的DOM操作

image.png

mixins 混入

混入就是复制

减少重复

类比

  • directives的作用是减少DOM操作的重复

  • mixins的作用减少datamethods钩子的重复

image.png

image.png

image.png

完成的代码链接:

codesandbox.io/s/brave-dij…

mixins技巧

  • 选项智能合并:见文档

  • Vue.mixin(不推荐使用)

image.png

extends(继承)

image.png

provide 和 inject(提供和注入)

image.png

总结

image.png