vue中全局公共方法和变量的使用

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)
     }
    )
  }

 

posted on 2022-02-03 21:54  一名小学生呀  阅读(4616)  评论(0编辑  收藏  举报

导航