1.在assets文件夾下,新建js文件夾,創建common.js
export default { istest(){ console.log("this is test") } }
2.如果是全局(多頁面)使用:在main.js中引入
/* 引入公共js*/ import common from '@/assets/js/common.js' Vue.prototype.common=common;
3..在VUE文件中使用
this.common.istest(); //this is test
如果是單頁面使用:
1.在vue的script中引入
import common from '@/assets/js/common'
2.在vue文件中使用
common.istest(); //this is test
代碼示例:
全局引入文件
1.先定義共用組件 common.vue
<script type="text/javascript"> // 定義一些公共的屬性和方法 const httpUrl = 'http://39.105.17.99:8080/' function commonFun() { console.log("公共方法") } // 暴露出這些屬性和方法 export default { httpUrl, commonFun } </script>
2.需要使用的地方導入
<script> // 導入共用組件 import global from './common.vue' export default { data () { return { username: '', password: '', // 賦值使用 globalHttpUrl: global.httpUrl } },
3.使用
<template>
{{globalHttpUrl}}
</template>
main.js中引入全局變量和方法
1.定義共用組件同上
2.main.js中引入並復制給vue
// 導入共用組件 import global from './common.vue' Vue.prototype.COMMON = global
3.使用
export default { data () { return { username: '', password: '', // 賦值使用, 可以使用this變量來訪問 globalHttpUrl: this.COMMON.httpUrl } }
定義common.js文件,直接在main.js中引入,直接使用
1.common.js 這里注意 Vue.http 組件中使用 this.$http
import Vue from 'vue' import VueResource from 'vue-resource' Vue.use(VueResource) const httpUrl = 'http://39.105.17.99:8080/' function httpGet (url, params) { return new Promise((resolve, reject) => { Vue.http.get(this.httpUrl + url, params).then( (res) => { resolve(res.json()) }, (err) => { reject(err.json()) } ) }) } function httpPost (url, params) { return new Promise((resolve, reject) => { Vue.http.post(this.httpUrl + url, params).then( (res) => { resolve(res.json()) }, (err) => { reject(err.json()) } ) }) } export default { httpUrl, httpGet, httpPost }
2.main.js注冊
import global from './common/common'
Vue.prototype.GLOBAL = global
3.使用
<template>
{{GLOBAL.httpUrl}}
</template>
created () { this.GLOBAL.httpGet('/home/list', {'name': 'zxc', 'password': '123'}).then( (res) => { console.log(res) } ) }