转自:https://blog.csdn.net/Start2019/article/details/110438844
多个 js 方法,不想用 vue.prototype
封装一个弹框为例:
在 components 文件夹下新增一个 js 文件夹,并在 js 文件夹下新增 index.js 文件。
import { MessageBox } from 'element-ui'
const handleconfirm = (text ='此操作将永久删除该文件, 是否继续?', type='warning') => {
// 这里 export后面不加 default,引用时:import {方法名} from js文件地址。因为每个文件常有多个方法,所以常用此方案
// export后加 default,引用时:import 方法名 from js文件地址
// 通过export方式导出,在导入时要加{ },export default则不需要
return MessageBox.confirm(text, '提示',{
confirmButtonText: '确定',
cancelButtonText: '取消',
type: type
})
}
export { handleconfirm }
export {} 和 export default {} 的区别
- export {}:引用时 import {方法名} from js文件地址;
- export default {}:引用时 import 方法名 from js文件地址
全局和局部使用的区别:笼统一点,全局注册在 main.js ,局部注册在需要调用的页面中。
import { handleConfirm } from '@/components/js'
<el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteData(scope.row.id)" >删除</el-button>
//删除
deleteData(id) {
handleConfirm().then( ()=> {
//调用删除接口
}).catch( ()=> {
this.$message.info("已取消删除!");
})
}
封装的方法较多,又想通过 this 直接调用
在 components 文件夹下新增一个 js 文件夹,并在 js 文件夹下新增 index.js 文件
import axios from 'axios';
import ElementUI from 'element-ui';
function getProcess(typeCode){
console.log(1)
axios.get('/api/temp/getParams?typeCode='+typeCode)
.then(res => {
console.log(res)
if( res.status == 200){
}
})
.catch(err =>{
this.$message.error('服务器响应失败');
console.log(err);
})
};
function alert(){
//...
}
export default {
getProcess, alert
}
在 main.js 中引入,并在原型的身上挂载。
import commonJS from '@/components/js'
Vue.prototype.$commonJS = commonJS;
this.$commonJS.getProcess("0001");
更多精彩内容:各种AI课程、技能课程、黑科技软件、网站小程序源码、副业小项目、PPT模板等精品素材、电商课程、推广引流课程等,尽在 天边资源网 。