Vue中如何引用公共方法和公共组件
作者:奥特蛋_mm
这篇文章主要介绍了Vue中如何引用公共方法和公共组件问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
vue引用公共方法和公共组件
vue中引用公共方法
1.在src新建commonFunction文件夹,再新建common.js

其中common.js中方法的声明和导出如下

2.在main.js中引用common.js,再使用Vue.prototype添加实例属性

3.应用
@click=“common.方法名”

vue中引用公共组件
1.在src目录下的components文件夹下新建公共组件

2.在main.js中引用,这里需要引用并初始化组件三个步骤
import AreaSelect from '@/components/AreaSelect'
Vue.use(AreaSelect) // 引用自定义组件
Vue.component('area-select', AreaSelect) // 初始化组件
new Vue({
el: '#app',
components: {
AreaSelect
},
})
3.直接用 area-select 即可使用
你不知道的Vue的公共组件?
1、组件是什么?
答:组件是包含数据、逻辑功能、展现样式的代码片段。
2、封装公共组件要注意哪些事项?
答:1)可读性。公共组件是团队协作的基础,可读性就显得尤为总要,怎么增加组件的可读性呢?首先组件命名要语义化,大家看到组件就一目了然,知道该组件的功能是啥;其次我们组件要有一个清晰明了的注释,演示组件用例,属性、参数、方法说明,让大家几乎不用动脑就可以完美使用。
1.什么是公共组件?
本质上是,多次使用一个组件
2.定义公共组件的·格式是什么?
Vue.component(‘组件名’)
3.组件对应的vue文件放在哪里?
放在components文件夹中
4.使用vue公共的组件
在components文件夹中创建1个vue文件
<template>
<el-card>
<div class="page-tools">
<div class="left">
<div class="tips">
<i class="el-icon-info" />
<span>
<!-- 具名插槽 -->
<slot name="left">文字区域</slot>
</span>
</div>
</div>
<!-- 右侧 -->
<div class="right">
<!-- 具名插槽 -->
<slot name="right" />
</div>
</div>
</el-card>
</template>
<script>
export default {}
</script>
<style lang="scss" scoped>
.page-tools {
display: flex;
justify-content: space-between;
align-items: center;
.tips {
line-height: 34px;
padding: 0px 15px;
border-radius: 5px;
border: 1px solid rgba(145, 213, 255, 1);
background: rgba(230, 247, 255, 1);
i {
margin-right: 10px;
color: #409eff;
}
}
}
</style>在使用的地方引入component创建的文件,在component里面定义
代码如下:
<template>
<div class="department-container">
<div class="app-container">
<page-tool>
<template #left>
总记录数:20条
</template>
<template #right>
<el-button type="warning">导入excel</el-button>
<el-button type="danger">导出excel</el-button>
<el-button type="primary">新增员工</el-button>
</template>
</page-tool>
<el-card>
<!-- 具体页面结构 -->
员工管理
</el-card>
</div>
</div>
</template>
<script>
import PageTool from '@/components/employes'
export default {
components: {
PageTool
}
}
</script>如果是全局组件的话是以下的方式 在main.js中引入,如下代码:
// 导入全局组件(公共组件) import PageTool from '@/components/employes' Vue.component(`PageTool`, PageTool)
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
