vue单独打包js文件

JavaScript016

vue单独打包js文件,第1张

刚开始学vue框架,公司要求项目打包的时候把服务器的ip地址单独留一个接口,方便后期商家可以自行配置自己的服务器地址。

解决办法:

1、新建一个js文件用于保存服务器的ip地址,将当前ip存入window对象,内容如下:

2、在webpack配置文件中找到plugins选项,配置插件:

3、在index.html文件中以script标签形式引入server.js(保存ip)文件,注意在打包的时候开发环境和生产环境的路径问题:

4、在main.js中将ip添加到vue原型中:Vue.prototype.ip = window.ip

5、最后在需要调用 的地方直接使用this.ip即可。

6、打包之后的目录结构,如果服务器的ip地址发生了变化,可直接修改server.js文件,然后保存。

1.首先创建一个js

ex: test.js 

const referrerPhone = [

  { pattern: /^1[3456789]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }

]

export default {

referrerPhone 

}

import validators  from '../路径/test.js'

定义成对象方便调用

Vue.prototype.$validators  = validators 

this.$validators.referrerPhone 

=======================================================================================================

第二种 不是公用

1.创建一个 js

// 弹框提示

function tips(this_, message_, type_){

  this_.$message({

    message: message_,

    type: type_

  })

export { //很关键

  tips,

}

import { tips} from '../xx.js'

tips(this, '非法操作,不能删除admin用户!', 'error')

封装接口

首先创建一个idnex.js文件

import axios from 'axios'

/* 创建一个axios实例化对象instance */

var instance = axios.create({

/* 基础路径 /

baseURL: 'url‘,

/设置超时时间 */timeout: 5000})

instance.interceptors.request.use(

config =>{

localStorage.token &&(config.headers.Authorization = localStorage.token)

return config

},

error =>{

return Promise.error(error)

}

)

axios.interceptors.response.use(response =>{

return response

},

error =>{

return error

})

/* 参数methods默认值是get,path表示具体路径,post需要给data传参默认值是空对象 get请求需要给params传参默认值是空对象 */

export const httpServe = (path,params={},method="get",data={})=>{

return new Promise((resolve,reject)=>{

instance({

method,

url:path,

params,/* get方法 */

data/* post方法 */

})

.then(res=>{

resolve(res)

})

.catch(err=>{

reject(err)

})

})

}

然后创建request.js文件写方法

import {httpServe} from '@/http/index.js'

/* 登录 */

export const loginPost = (path,data)=>httpServe(path,{},'post',data)

/* 用户列表 */

export const usersGet = (path,params)=>httpServe(path,params)

/* 获取左侧菜单列表 */

export const menusGet = (path,params)=>httpServe(path,params)

/* 添加用户 */

export const addusersPost = (path,data)=>httpServe(path,{},'post',data)