当前位置: 代码网 > it编程>前端脚本>Vue.js > vue引入组件的几种方法代码示例

vue引入组件的几种方法代码示例

2024年05月15日 Vue.js 我要评论
一、常用的局部引入<template> <div> <!--3.使用组件--> <button></button

一、常用的局部引入

<template>
    <div>
        <!--3.使用组件-->
        <button></button>
    </div>
</template>

<script>
 // 1. 引入组件
import button from '../view/button.vue'
export default {
    // 2. 注册组件
    components: {
        button,
    }
}
</script>

总结: 在哪个页面需要就在那个页面引入、注册、使用

二、创建一个js 进行统一注册   然后在main.js引入统一管理的js文件实现全局注册

1、global.js统一注册管理:

// 1.引入vue
import vue from 'vue'
import  child1 from './child1'
import  child2 from './child1'
import  child3 from './child1'
import  child4 from './child1'
import  child5 from './child1'

vue.component(child1)
vue.component(child2)
vue.component(child3)
vue.component(child4)
vue.component(child5)

2、在main.js中引入 global.js实现全局注册

优点: 减少每个页面引入的繁琐步骤 、减少了每一页面重复引入的代码,

缺点: 有90%的代码都是重复的

三、自动注册全局引入

注释版:

// 引入vue
import vue from 'vue'
// 将字符串首字母大写  返回当前字符串
function changestr(str) {
    return str.charat(0).touppercase() + str.slice(1)
}
// require.context: 是动态引入文件
// 参数一: 当前路径(引入.vue文件的当前路径)
// 参数二:是否匹配当前文件下的子文件
// 参数三:查找文件格式以.vue结尾的文件
const requirecomponent = require.context('./', false, /\.vue$/)
console.log("批量注册组件", requirecomponent.keys())  // ['./head-l.vue', './head-r.vue', './head.vue']
requirecomponent.keys().foreach(filename => {
	// 当前组件
    const config = requirecomponent(filename)
	console.log("组件的信息config", config)
	//获取组件名
	const componentname = changestr(filename.replace(/^\.\//, '').replace(/\.\w+$/))  // 第一个replace(/^\.\//, '')去掉前面的./   第二个replace(/\.w+$/)是去掉后面的.vue
	console.log("组件名", componentname)  // 例如:head-rundefined
	// 参数一: 组件名
	// 参数二: config:是一整个组件的内容;  config.default:是组件中export.default里面的内容  
	vue.component(componentname, config.default || config)
	
})

 纯净版:

import vue from 'vue'
function changestr(str) {
    return str.charat(0).touppercase() + str.slice(1)
}
const requirecomponent = require.context('./', false, /\.vue$/)
requirecomponent.keys().foreach(filename => {
    const config = requirecomponent(filename)
	const componentname = changestr(filename.replace(/^\.\//, '').replace(/\.\w+$/))  
	vue.component(componentname, config.default || config)
	
})

 结构: 

附:vue 中 import引入相同的方法名称解决方法

import { list } from '@/api/aaaa/apijs'
import { list} from '@/api/bbb/apijs'

当引入了2个不同的文件,方法名称list都是一样的,就会出现报错。

如果之前文件用的地方比较多,直接改名称的话,可能会漏掉,会引起不必要的麻烦,那如何解决呢

解决方法:

import { list } from '@/api/aaaa/apijs'
import { list as _list} from '@/api/bbb/apijs'

就是使用 import as

as后面的名字就是你要替换的名称,是不是很简单就解决了

总结 

到此这篇关于vue引入组件的几种方法的文章就介绍到这了,更多相关vue引入组件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com