美文网首页
2020-12-30

2020-12-30

作者: 二荣xxx | 来源:发表于2021-01-04 12:21 被阅读0次

    Vue的高级属性

    一、directive指令

    directive指令官方文档,指令的作用:主要用于DOM操作(DOM操作常用或复杂可封装为指令)

    声明全局指令

    Vue.directive('x',{directiveOptions})
    

    使用:v-x 全局可用

    声明局部指令

    new vue({
        directives:{
          'x':directiveOptions
      }
    })
    

    使用:v-x 该实例可用

    directionOptions:选项

    • bind: function () {} 类似created
    • inserted: function () {}, 类似mounted
    • update: function () {}, 类似updated
    • componentUpdated: function () {},
    • unbind: function () {} 类似destroyed
      以上参数有:el、info、vnode、oldvnode,

    代码举例

    <template>
      <div>
        {{ xxx }}
        <button v-x>xxx</button>
        <button v-on2:click="hi">v-on2</button>
      </div>
    </template>
    
    <script>
    export default {
      data() {
        return {
          xxx: 111,
        };
      },
      directives: {
        x: {
          inserted: function (el) {
            el.addEventListener("click", () => {
              console.log("x");
            });
          },
        },
        on2: {
          inserted(el, info) {
            console.log(el, info);
            el.addEventListener(info.arg, info.value); //获取事件和函数
          },
          unbind(el, info) {
            el.removeEventListener(info.arg, info.value); //清理监听
          },
        },
      },
      methods: {
        hi() {
          console.log("on2-hi");
        },
      },
    }
    

    二、mixins混入

    mixin代码示例
    全局

    Vue.mixin({})
    

    局部

    Options.mixins:[mixin1,mixin2]
    

    作用:减少data、methods、钩子的重复
    格式:mixins:[log]
    log是存的需要复制的内容,可以写在一个文件内导出使用

    export default log  //导出
    import log from '原log文件路径'  //导入
    

    三、extend

    extend代码示例与mixin差不多只是形式不一样
    声明:

    const  MyVue   = Vue.extend({'需要继承的内容'}) //然后导出 全局
    
    Options.extends:{...} //局部
    

    使用(现导入)

    extends:MyVue 
    

    四、provide和inject

    provide和inject代码示例
    作用:祖先提供东西,后代注入东西,大范围的data和method共用
    注意:不能只传themeName不传changeTheme,因为themeName的值是要被复制给provide的

    相关文章

      网友评论

          本文标题:2020-12-30

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