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

vue中全局公共方法和变量的使用1.在assets文件夹下,新建js文件夹,创建common.jsexportdefault{istest(){console.log("thisistest")}}2.如果是全局(多页面)使用:在main.js中引入/*引入公共js*/importc

大家好,欢迎来到IT知识分享网。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)
     }
    )
  }

 

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/27630.html

(0)
上一篇 2023-11-29 21:33
下一篇 2023-12-16 11:00

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信