方法 1(简单,但不推荐)
1 2 3 4 5 6 7 8 9 10 11 12 | mounted() {<!-- --> // 2. 在mounted阶段声明globalFn,来调用组件内的方法 window.globalFn = () => {<!-- --> this.getDetail() } }, methods: {<!-- --> // 1. 组件内有一个getDetail方法,需要暴露给window,以供嵌入该页面的客户端调用 getDetail() {<!-- --> // 业务逻辑 } } |
优点:
- 简单: 适合暴露的方法不太多的系统
缺点:
-
变量名易冲突: 如果需要暴露的方法越来越多,那么 window 对象中的全局变量也会越来越多,容易变量名冲突
-
位置分散: 随着业务的复杂化,暴露的方法可能分散在各个.vue 文件中,不容易管理
方法 2(推荐,解决方法 1 的痛点)
- 在
main.js 中把Vue 对象暴露给window
1 2 3 4 5 6 7 8 | // ... const vm = new Vue({<!-- --> router, store, render: (h) => h(App) }).$mount('#app') window.vm = vm // 只把vm暴露给window,以后都在vm中做文章 // ... |
- 在一个你喜欢的目录下新建 js 文件,该文件用来存放需要暴露出去的方法
(我是把这个文件放在了 @/utils/export2vmFunction.js 下)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | exports.install = function (Vue) {<!-- --> // 把需要暴露出去的方法挂载到Vue原型上,避免了全局变量过多的问题 // 全局方法都在这里,方便管理 Vue.prototype.globalFn1 = function () {<!-- --> const component = findComponentDownward(this, 'RecommendRecord1') component.getDetail1() } Vue.prototype.globalFn2 = function () {<!-- --> const component = findComponentDownward(this, 'RecommendRecord2') component.getDetail2() } // ... } /** * 由一个组件,向下找到最近的指定组件 * @param {*} context 当前上下文,比如你要基于哪个组件来向上寻找,一般都是基于当前的组件,也就是传入 this * @param {*} componentName 要找的组件的 name */ function findComponentDownward(context, componentName) {<!-- --> const childrens = context.$children let children = null if (childrens.length) {<!-- --> for (const child of childrens) {<!-- --> const name = child.$options.name if (name === componentName) {<!-- --> children = child break } else {<!-- --> children = findComponentDownward(child, componentName) if (children) break } } } return children } |
注:如果对上述找组件的方法不熟悉的小伙伴可以移步到:找到任意组件实例的方法
- 把目光在回到
main.js 中,导入刚刚声明好的 js 文件
1 2 3 4 5 | // ... import Vue from 'vue' import vmFunction from '@/utils/export2vmFunction' Vue.use(vmFunction) // ... |
- 大功告成
经过上述三步操作后,就可以用
优点:
-
方便管理: 所有方法都在一个文件中
-
全局变量少: 只有
vm 一个变量