Vue 的进阶构造属性

2023-01-08  本文已影响0人  茜Akane

1. Directive 指令

1.1 用 directive 自定义一个指令

Vue.directive("x", {
  inserted: function (el) {
    el.addEventListener("click", () => {
      console.log("x");
    });
  }
});

通过文档给出的方法创建一个自定义指令 v-x ,这种指令是全局变量,在别的文件也可以使用。

export default {
  name: "HelloWorld",
  props: {
    msg: String,
  },
  directives: {
    x: {
      inserted(el) {
        el.addEventListener("click", () => {
          console.log("x");
        });
      },
    },
  },
};

可以写进组件里,但其作用域只在这个组件内部可以使用。

1.2 directive 的五个函数属性(钩子函数)

属性参数:

Vue.directive("on2", {
  inserted(el, info) {
    // inserted 可以改为 bind
    console.log(info);
    el.addEventListener(info.arg, info.value);
    // Vue 自带的 v-on 并不是这样实现的,它更复杂,用了事件委托
  },
  unbind(el, info) {
    el.removeEventListener(info.arg, info.value);
  }
});
// app.vue
<div v-on2:click="sendLog">这是on2</div>

arg:传给指令的参数,可选。例如 v-on2:click 中,参数为 "click"。
value:指令的绑定值,这里是click中传入的函数。
函数简写
想在 bind 和 update 时触发相同行为,而不关心其它的钩子可以这样写,但是大多数时间写清楚钩子会更加容易阅读和维护。

Vue.directive('color-swatch', function (el, binding) {
  el.style.backgroundColor = binding.value
})

1.3 指令的作用

2 mixins 混入

2.1 减少重复

类比

场景描述
假设一种情况,现有五个子组件,都需要监听其组件的created、destroyed时间,并且打印出存活时间。

  1. 先来思考一下,如何实现监听和获取时间。
// Child1.vue
<template>
  <div>Child1</div>
</template>

<script>
export default {
  data() {
    return {
      name: "Child1",
      time: undefined,
    };
  },
  created() {    // 出生的时候取时间
    this.time = new Date();
    console.log(`${this.name}出生了`);
  },
  beforeDestroy() {    // 在元素消亡之前取值,所以不能用destroyed
    const now = new Date();
    console.log(`${this.name}消亡了,共生存了 ${now - this.time} ms`);
  },
};
</script>

然后在使用子组件的文件App.vue中,用v-if="标志位"设置button开关。

    <Child1 v-if="child1Visible" />
    <button @click="child1Visible = false">x</button>
  1. 这样就实现了Child1,其他四个组件也都是一摸一样,所以我们可以创建一个共通文件 ./mixins/log.js 把相同操作全部规整到这里。
const log = {
  data() {
    return {
      name: undefined,
      time: undefined
    };
  },
  created() {
    if (!this.name) {
      throw new Error("need name");
    }
    this.time = new Date();
    console.log(`${this.name}出生了`);
  },
  beforeDestroy() {
    const now = new Date();
    console.log(`${this.name}死亡了,共生存了 ${now - this.time} ms`);
  }
};
export default log;

Child五个组件除了name不同,省去重复代码就可以简化成如下所示。

<script>
import log from "../mixins/log.js";
export default {
  data() {
    return {
      name: "Child1"
    };
  },
  created() {
    console.log("Child 1 的 created");
  },
  mixins: [log]
};
</script>

2.2 mixins技巧

选项合并
选项智能合并文档
也可以使用全局Vue.mixin 但不推荐使用

3. extends 继承、扩展

extends也是构造选项里的一个选项,跟mixins很像,也是复制减少重复但形式不同。extends更抽象高级,但还是推荐用mixins。
步骤
1.新建文件MyVue.js,这不是Vue组件。

import Vue from "vue"
const MyVue = Vue.extend({ //继承Vue,MyVue就是Vue的一个扩展
  data(){ return {name:'',time:undefined} },
  created(){
    if(!this.name){console.error('no name!')}
    this.time = new Date()
  },
  beforeDestroy(){
    const duration = (new Date()) - this.time
    console.log(`${this.name} ${duration}`)
  },
  //mixins:[log] 也可以使用mixins
})
export default MyVue

2.导入+继承

Child1.vue
<template>
  <div>Child1</div>
</template>
<script>
import MyVue from "../MyVue.js";
export default{
  extends:MyVue,
  data(){
    return {
      name:"Child1"
    }
  }
}
</script>

extends是比mixins更抽象一点的封装。如果嫌写5次mixins麻烦,可以考虑extends一次,不过实际工作中用的很少。

4. provide(提供) 和 inject(注入)

举个例子,按下相关按钮改变主题和颜色。

<template>
  <div :class="`app theme-${themeName} fontSize-${fontSizeName}`">
<!-- 这里的双引号是XML的双引号,里面的才是js字符串 -->
    <Child1 />
    <button>x</button>
  </div>
</template>
<script>
import Child1 from "./components/Child1.vue";
export default {
  provide() {      // 将提供给外部使用的变量provide出去
    return {
      themeName: this.themeName,
      changeTheme: this.changeTheme,
      changeFontSize: this.changeFontSize,
    };
  },
  name: "App",
  data() {
    return {
      themeName: "blue", // 'red'
      fontSizeName: "normal", // 'big' | 'small'
    };
  },
  components: {
    Child1,
  },
  methods: {
    changeTheme() {
      if (this.themeName === "blue") {
        this.themeName = "red";
      } else {
        this.themeName = "blue";
      }
    },
    changeFontSize(name) {    
      if (["big", "nomal", "small"].indexOf(name) >= 0) {
        this.fontSizeName = name;
      }
    },
  },
};
</script>
// ChangeThemeButton.vue
<template>
  <div>
    <button @click="changeTheme">换肤</button>
    <button @click="changeFontSize('big')">大字</button>
    <button @click="changeFontSize('small')">小字</button>
    <button @click="changeFontSize('normal')">正常字</button>
  </div>
</template>
<script>
export default {
  inject: ["themeName", "changeTheme", "changeFontSize"]    // 将App.vue中provide出来的数据inject进这个组件
};
</script>

小结

  provide() {      // 将提供给外部使用的变量provide出去
    return {
      themeName: {value: this.themeName},
      changeTheme: this.changeTheme,
      changeFontSize: this.changeFontSize,
    };
  },

总结

上一篇下一篇

猜你喜欢

热点阅读