vue怎么定义全局变量和全局方法

其他教程   发布日期:2025年04月10日   浏览次数:222

本篇内容介绍了“vue怎么定义全局变量和全局方法”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

一、给vue定义全局变量

1.定义专用模块来配置全局变量

定义一个专用模块来配置全局变量,然后通过export暴露出去,在需要的组件引入global.vue

  1. // 定义一些公共的属性和方法
  2. const httpUrl = 'http://test.com'
  3. // 暴露出这些属性
  4. export default {
  5. httpUrl,
  6. }

引入及使用

  1. <script>
  2. // 导入共用组件
  3. import global from './global.vue'
  4. export default {
  5. data () {
  6. return {
  7. //使用
  8. globalUrl: global.httpUrl
  9. }
  10. }
  11. }
  12. </script>

2.通过全局变量挂载到Vue.prototype

同上,定义一个专用模块来配置全局变量,然后通过export暴露出去,在需要的组件引入global.vue

  1. // 定义一些公共的属性和方法
  2. const httpUrl = 'http://test.com'
  3. // 暴露出这些属性
  4. export default {
  5. httpUrl,
  6. }

在main.js中引入并复制给vue

  1. // 导入共用组件
  2. import global from './global.vue'
  3. Vue.prototype.global = global

组件调用

  1. export default {
  2. data () {
  3. return {
  4. // 赋值使用, 可以使用this变量来访问
  5. globalHttpUrl: this.global.httpUrl
  6. }
  7. }

3.使用vuex

安装:

  1. npm install vuex --save

新建store.js文件

  1. import Vue from 'vue'
  2. import Vuex from 'vuex';
  3. Vue.use(Vuex);
  4. export default new Vuex.Store({
  5. state:{ httpUrl:'http://test.com' }
  6. })

main.js中引入

  1. import store from './store'
  2. new Vue({
  3. el: '#app',
  4. router,
  5. store,
  6. components: { App },
  7. template: '<App/>'
  8. });

组件内调用

  1. console.log(this.$store.state.httpUrl)

二、给vue定义全局方法

1.将方法挂载到 Vue.prototype 上面

简单的函数可以直接写在

  1. main.js
文件里定义。

  1. // 将方法挂载到vue原型上
  2. Vue.prototype.changeData = function (){
  3. alert('执行成功');
  4. }

使用方法

  1. //直接通过this运行函数,这里this是vue实例对象
  2. this.changeData();

2. 利用全局混入 mixin

新建一个mixin.js文件

  1. export default {
  2. data() {
  3. },
  4. methods: {
  5. randomString(encode = 36, number = -8) {
  6. return Math.random() // 生成随机数字,
  7. .toString(encode) // 转化成36进制
  8. .slice(number)
  9. }
  10. }
  11. }

// 在项目入口 main.js 里配置

  1. import Vue from 'vue'
  2. import mixin from '@/mixin'
  3. Vue.mixin(mixin)

// 在组件中使用

  1. export default {
  2. mounted() {
  3. this.randomString()
  4. }
  5. }

3. 使用插件方式

  1. plugin.js
文件,文件位置可以放在跟
  1. main.js
同一级,方便引用

  1. exports.install = function (Vue, options) {
  2. Vue.prototype.test = function (){
  3. console.log('test');
  4. };
  5. };

  1. main.js
引入并使用。
  1. import plugin from './plugin'
  2. Vue.use(plugin);

所有的组件里就可以调用该函数。

  1. this.test();

以上就是vue怎么定义全局变量和全局方法的详细内容,更多关于vue怎么定义全局变量和全局方法的资料请关注九品源码其它相关文章!