11.vue函数挂载到window对象

2023-02-27  本文已影响0人  zouhao1985

一、概述

最近项目中需要与其他系统集成,其他系统通过获取页面上的HTML内容来进行集成。因此需要提供一种JS的方式来执行网站的脚本。由于网站是基于VUE开发的,通过搜索资料,有两种方式将VUE的方法挂载到window对象。话不多说,直接上代码片段。

二、挂载方式一

    mounted() {
      // 第一种挂载方式
      window.jsLogin = this.jsLogin
    },
    methods: {
        // jsLogin挂载到window对象
        jsLogin(username, password) {
          this.username = username
          this.passowrd = password
          this.login()
        },
        login() {
            console.log('login username: ' + this.username + ', pwd: ' + this.passowrd)
            sessionStorage.setItem('username', this.username)
            // httpGet('/api')
            httpGet('/api/user/get/1')
            this.$router.push({path: '/dashboard/dashboard1'})
        }
    },

通过mounted方法挂载方法到对应的属性中,其中jsLogin是自定义的属性,指向VUE的jsLogin方法。
测试方式:启动网页后,F12调出控制台,输入window.jsLogin('panda','mypwd') 实现登录。


image.png

三、挂载方式二

    // 注意这里需要 import Vue from 'vue'
    mounted() {
      // 第一种挂载方式
      window.jsLogin = this.jsLogin
      // 第二种挂载方式
      Vue.prototype.jsLogin = this.jsLogin
    },
    methods: {
        // jsLogin挂载到window对象
        jsLogin(username, password) {
          this.username = username
          this.passowrd = password
          this.login()
        },
        login() {
            console.log('login username: ' + this.username + ', pwd: ' + this.passowrd)
            sessionStorage.setItem('username', this.username)
            // httpGet('/api')
            httpGet('/api/user/get/1')
            this.$router.push({path: '/dashboard/dashboard1'})
        }
    },
// main.js 第二种挂载方式
window.vm = new Vue({
  router,
  store,
  render: h => h(App),
}).$mount('#app')

测试方式:启动网页后,F12调出控制台,输入window.vm.jsLogin('panda','mypwd') 实现登录。


image.png

四、源码地址

https://gitee.com/animal-fox_admin/learn-vue-web
branch:lesson6

上一篇下一篇

猜你喜欢

热点阅读