Vue进阶(贰幺零):Vue 全局函数、组件、变量挂载方式_vue main,前端最牛教材

44 阅读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.installvue的插件语法糖,方便用vue.use 使用的。

四、全局组件挂载

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

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

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

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

五、拓展阅读

计算机网络

  • HTTP 缓存

  • 你知道 302 状态码是什么嘛?你平时浏览网页的过程中遇到过哪些 302 的场景?

  • HTTP 常用的请求方式,区别和用途?

  • HTTPS 是什么?具体流程

  • 三次握手和四次挥手

  • 你对 TCP 滑动窗口有了解嘛?

  • WebSocket与Ajax的区别

  • 了解 WebSocket 嘛?

  • HTTP 如何实现长连接?在什么时候会超时?

  • TCP 如何保证有效传输及拥塞控制原理。

  • TCP 协议怎么保证可靠的,UDP 为什么不可靠?

算法

  • 链表

  • 字符串

  • 数组问题

  • 二叉树

  • 排序算法

  • 二分查找

  • 动态规划

  • BFS

  • DFS

  • 回溯算法

开源分享:docs.qq.com/doc/DSmRnRG…