vue全局注册组件和自定义指令


一 vue 2

1 全局注册组件

src下创建component/index.js文件

// 导入相关组件
import '注册组件名' from './...'
export default {
 install (Vue) {
  Vue.component('要使用时的名称', 注册组件名 )  
 }
}

main.js中导入注册

import Component from '@/component'
Vue.use (Component ) //注册自己的组件

组件使用

<template>
	<div>
	    // 第一种方式
	    <要使用时的名称/>
	   // 第二种方式
	   <component :is='组件名' />
	</div>
</template>

2 自定义指令

export default {
	Vue.directive('指令名', {
	  // el 当前元素,bind.value 可访问传入的值
	  inserted (el, bind) { 
	     el.xxx = bind.value
	   }
	 })
 }

新建 src下新建tools/directive.js文件

export const LazyLoad = () => {
  // el 当前元素,bind.value 可访问传入的值
    Vue.inserted (el, bind) { 
     el.xxx = bind.value
   }


}

main.js中注册使用

import Vue from 'vue'
import Directives from './utils/directives'
Vue.use(Directives)

二 vue3

1 全局注册组件和自定义指令

创建 components/library/index.js

export default {
  install (app) {
    // 自定义组件
    app.component(XtxSkeleton.name, XtxSkeleton)
    app.component(xtxCarousel.name, xtxCarousel)
    app.component(xtxMore.name, xtxMore)
    // 自定义指令
    defineDirective(app)
  }
}
const defineDirective = (app) => {
  // directive('指令名称',fn)自定义指令
  app.directive('lazy', {
    // vue 2.0用inserted 监听DOM是否创建好
    // vue3.0 用mounted
    mounted (el, binding) { // el监听的元素,binding传入的值
      const observer = new IntersectionObserver(([{ isIntersecting }]) => {
        // 是否进入可视区
        if (isIntersecting) {
          // 停止观察
          observer.unobserve(el)
          // 图片加载失败
          el.onerror = () => {
            el.src = defaultImg
          }
          el.src = binding.value
        }
      }, {
        // 进入可视区立即开始
        threshold: 0
      })
      // 开启观察
      observer.observe(el)
    }
  })
}

main.js 中注册

import ui from './components/library'

createApp(App).use(ui).mount('#app')
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值