把组件方法暴露到window对象中
方法 1(简单,但不推荐)
mounted() { ? // 2. 在mounted阶段声明globalFn,来调用组件内的方法 ? window.globalFn = () => { ? ? this.getDetail() ? } }, methods: { ? // 1. 组件内有一个getDetail方法,需要暴露给window,以供嵌入该页面的客户端调用 ? getDetail() { ? ? // 业务逻辑 ? } }
优点:
简单: 适合暴露的方法不太多的系统缺点:
变量名易冲突: 如果需要暴露的方法越来越多,那么 window 对象中的全局变量也会越来越多,容易变量名冲突 位置分散: 随着业务的复杂化,暴露的方法可能分散在各个.vue 文件中,不容易管理
方法 2(推荐,解决方法 1 的痛点)
1. 在 main.js 中把 Vue 对象暴露给 window
// ... const vm = new Vue({ ? router, ? store, ? render: (h) => h(App) }).$mount('#app') window.vm = vm // 只把vm暴露给window,以后都在vm中做文章 // ...
2. 在一个你喜欢的目录下新建 js 文件,该文件用来存放需要暴露出去的方法
(我是把这个文件放在了 @/utils/export2vmFunction.js 下)
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 }
注:如果对上述找组件的方法不熟悉的小伙伴可以移步到: 找到任意组件实例的方法
3. 把目光在回到 main.js 中,导入刚刚声明好的 js 文件
// ... import Vue from 'vue' import vmFunction from '@/utils/export2vmFunction' Vue.use(vmFunction) // ...
4. 大功告成
经过上述三步操作后,就可以用vm.globalFn1()来调用组件内的方法了
优点:
方便管理: 所有方法都在一个文件中 全局变量少: 只有vm一个变量
将方法绑定到window对象下,给app端调用
通过jsBridge方法,H5可以调用客户端(ios,android)的内部方法,
同样,客户端也需要能调用H5页面里定义的js方法,
但是在vue里,所有的方法都是在组件内部声明的,也只能在组件内部调用,
原生调用h5方法必须定义在window对象下
mounted(){ // 将scanResult方法绑定到window下面,提供给原生调用 //(方法名scanResult是原生定义好的,扫描成功后会主动调用window下的该方法) window['scanResult'] = (val) => { this.getScanVal(val) } }, methods:{ //原生调用scanResult方法后执行getScanVal方法,获取到val getScanVal(val){ console.log('扫一扫获取到的:'+ val) }, //点击事件调取扫一扫功能 doScan(){ this.demo.doScan()//调用原生方法开启扫一扫 }, }
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
查看更多关于vue如何把组件方法暴露到window对象中的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did120845