vaakian / vaakian.github.io

some notes
https://vaakian.github.io
3 stars 0 forks source link

Vue高阶开发 #12

Open vaakian opened 4 years ago

vaakian commented 4 years ago

Vue高阶开发

一、插件开发

插件暴露一个install方法,使用Vue.use()安装该插件。

// userVideo.vue组件
<template>
// 透传所有参数、属性、监听
  <video v-bind="{...$props, ...$attrs, ...$listeners}" ref="userVideo"></video>
</template>
<script>
export default {
  props: {
    height: {
      type: [Number, String],
      default: 200
    },
    width: {
      type: Number,
      default: 200
    },
    autoplay: {
      type: Boolean,
      default: true
    },
    controls: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {};
  },
  methods: {
    initLocalVideo() {
      const el = this.$refs.userVideo;
      navigator.mediaDevices
        .getUserMedia({ video: true, audio: true })
        .then(mediaStream => {
          el.srcObject = mediaStream;
          el.autoplay = true;
        })
        .catch(reason => {
          throw new Error(reason);
        });
    }
  },
  mounted() {
    this.initLocalVideo();
  }
};
</script>
// MyPlg.js
import UserVideo from '../components/UserVideo'
export default {
  install(Vue, options) {
// 注册全局组件,使用<v-cam />
    Vue.component('v-cam', UserVideo);
    Vue.directive('cam', {
      bind() { },
// 注册全局指令,使用<video v-cam />
      inserted(el, binding, vnode, oldVnode) {
        if (el instanceof HTMLVideoElement) {
          navigator.mediaDevices.getUserMedia({ video: true, audio: true })
            .then(mediaStream => {
              el.srcObject = mediaStream;
              el.autoplay = true;
            }).catch(reason => {
              throw error(reason)
            });
        } else {
          throw error('the element is not HTMLVideoElement')
        }
      },
      update() {

      },
      componentUpdated() {

      },
      unbind() {

      }
    })
  }
}

钩子函数

一个指令定义对象可以提供如下几个钩子函数 (均为可选):

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

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

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

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

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

钩子函数参数

指令钩子函数会被传入以下参数: