如何在vue js中访问window对象?

Tos*_*kan 4 vue.js vuejs2

我有这个vue js组件:

<template>
    <div>
hello world
    </div>
</template>

<script>
  export default {
    name: 'mycomp',
    data: function () {
      console.error("window.google_recaptcha_public_key", window.google_recaptcha_public_key);
      return {

      }
    },
    mounted() {
      let app = this;
      console.error("window.google_recaptcha_public_key2", window.google_recaptcha_public_key);

    },
  }
</script>

<style scoped lang="scss">
</style>
Run Code Online (Sandbox Code Playgroud)

返回:

window.google_recaptcha_public_key undefined 
window.google_recaptcha_public_key2 undefined
Run Code Online (Sandbox Code Playgroud)

在哪里可以使所有全局配置轻松自如呢?

注意此配置位于我的laravel后端中。所以我不会将所有值从后端复制粘贴到前端

bbs*_*nbb 22

在 Vue3 中,您不再拥有全局 Vue 实例,因此您需要将窗口分配为应用程序上的全局属性...

// main.js
app.config.globalProperties.window = window
Run Code Online (Sandbox Code Playgroud)

然后在你的组件中,window就可以工作了。

此信息来自无可挑剔的来源

  • 诚实地做这件事是一种可怕的方式,例如,你被迫这样做……例如,可怕的是,这不是更明显的做法。看起来很不务实 (3认同)

Ily*_*nko 10

你应该在Vue.prototype 中保存你的窗口变量

主文件

Vue.prototype.$authUser = window.authUser;
Run Code Online (Sandbox Code Playgroud)

之后,您可以按如下方式访问您的数据:

Vue模板

<div v-text="$authUser.name"></div>
Run Code Online (Sandbox Code Playgroud)

Vue 脚本

let name = this.$authUser.name;
Run Code Online (Sandbox Code Playgroud)


Mou*_*man 8

U可以Vue.prototypemain.js文件中使用,也可以在文件中使用import Vue

Vue.prototype.Hereanyname = window.hereanyname;
Run Code Online (Sandbox Code Playgroud)

在您的Vue应用程序中,您可以使用它

Hereanyname.thefunction
Run Code Online (Sandbox Code Playgroud)

真实的例子 Laravel

main.js

import Vue from 'vue';
Vue.prototype.Routes = window.routes;

new Vue({
    el: '#app',
    template: '<App/>',
    components: {App}
});
Run Code Online (Sandbox Code Playgroud)

在您的应用程序中

:href="Routes.route('laravel.route.here')"
Run Code Online (Sandbox Code Playgroud)

所以对于你的情况

import Vue from 'vue';
Vue.prototype.GoogleRecaptcha = window.google_recaptcha_public_key;

new Vue({
    el: '#app',
    template: '<App/>',
    components: {App}
});
Run Code Online (Sandbox Code Playgroud)

内部应用

mounted() {
  console.log(this.GoogleRecaptcha)
}
Run Code Online (Sandbox Code Playgroud)


ant*_*ore 5

提供/注入效果很好。这是 Vue 3 的示例:

main.js

const app = createApp(App)
app.provide('recaptcha_key', window.google_recaptcha_public_key)
app.mount('#app')
Run Code Online (Sandbox Code Playgroud)

我的组件.vue

<script setup>
const { inject } from 'vue'
const recaptchaKey = inject('recaptcha_key')
</script>
Run Code Online (Sandbox Code Playgroud)