本网站(662p.com)打包出售,且带程序代码数据,662p.com域名,程序内核采用TP框架开发,需要联系扣扣:2360248666 /wx:lianweikj
精品域名一口价出售:1y1m.com(350元) ,6b7b.com(400元) , 5k5j.com(380元) , yayj.com(1800元), jiongzhun.com(1000元) , niuzen.com(2800元) , zennei.com(5000元)
需要联系扣扣:2360248666 /wx:lianweikj
Vue进阶(贰幺零):Vue 全局函数、组件、变量挂载方式
makebo · 114浏览 · 发布于2023-06-29 +关注

一、前言

项目开发过程中,定义的方法、变量、组件如果被多处引用,就要考虑将其抽取为公共部分,提升代码复用度,便于维护。

二、全局变量挂载

有以下两种方式可实现全局挂载全局变量。

2.1 方式一:Vue.prototype

1、添加实例 property

你可能会在很多组件里用到数据/实用工具,但是不想污染全局作用域。这种情况下,你可以通过在原型上定义它们使其在每个 Vue 实例中可用。

Vue.prototype.$appName = 'My App'

这样 $appName 就在所有的 Vue 实例中可用了,甚至在实例被创建之前就可以。如果我们运行:

new Vue({
  beforeCreate: function () {
    console.log(this.$appName)
  }
})

则控制台会打印出 My App。就这么简单!

2.2 对象引入

1、新建 global_variable.js文件,用于存放变量,示例如下:

const startDate = new Date(new Date() - 24 * 60 * 60 * 1000 * 30)
const endDate =  new Date()
const dataText = ''//表格置空
export default {
    startDate,
    endDate,
    dataText,
}

全局使用,示例如下:

import globalVariable from './assets/js/global_variable'
Vue.prototype.GLOBAL = globalVariable

在需要使用的模块文件中使用(无需引入,直接通过this使用),示例如下:

data() {
      return {
        startDate: this.GLOBAL.startDate, //开始时间
        endDate: this.GLOBAL.endDate, //结束时间
        dataText: this.GLOBAL.dataText, //表格开始置空
      };
    },

注⚠️:务必以$开头,否则会命名冲突!

三、全局挂载全局函数

有很多函数在重复使用,所以,我们可以对这些函数进行全局挂载,省时又省力!

实现过程如下:

  1. 单独新建一个全局变量模块文件,模块中定义一些变量初始状态,用export default 暴露出去;

  2. 在main.js中引入,并通过Vue.prototype挂载到vue实例上面。供其他模块文件使用;

  3. 或者直接引入到需要的模块文件中使用;

有以下两种方式可实现全局挂载全局函数。

3.1 方式一:Vue.prototype

在main.js加入

// Vue 全局挂载自定义函数
// folding为传进来的参数
// internalFolding 为函数名
 
Vue.prototype.internalFolding = function (folding){
    //函数内容
}

在所有组件里可调用函数

this.internalFolding(folding)

这里的引用方式不推荐使用,因为所有的引用都放到main.js中会显得很乱!

3.2 方式二:exports.install + Vue.prototype

写好自己需要的公共JS文件(folding.js)

exports.install = function (Vue, options) {
  Vue.prototype.internalFolding = function (folding){
      if(folding){
          $(".abnormal-center-right").css("left","1%");
          }else{
           $(".abnormal-center-right").css("left","21%");
          }
  };
};

main.js 引入并使用

import folding from '@/static/js/folding'
Vue.use(folding);

所有组件里可调用函数

this.internalFolding(this.folding);

这里的引用方式推荐使用!

注:exports.install为vue的插件语法糖,方便用vue.use 使用的。

四、全局组件挂载

在main.js中全局注册到vue中。

import MyBread from '@/components/common/MyBread.vue'
Vue.component("MyBread", MyBread);//全局自定义组件

在需要的组件中可以直接使用,注意需要父子传值

<MyBread level1="用户管理" level2="用户列表"></MyBread>

相关推荐

PHP实现部分字符隐藏

沙雕mars · 1325浏览 · 2019-04-28 09:47:56
Java中ArrayList和LinkedList区别

kenrry1992 · 908浏览 · 2019-05-08 21:14:54
Tomcat 下载及安装配置

manongba · 970浏览 · 2019-05-13 21:03:56
JAVA变量介绍

manongba · 963浏览 · 2019-05-13 21:05:52
什么是SpringBoot

iamitnan · 1086浏览 · 2019-05-14 22:20:36
加载中

0评论

评论
没有最好,只有更好,一切都在路上!
分类专栏
小鸟云服务器
扫码进入手机网页