How to access the window object in vue js?

2020-06-17 04:22发布

I have this vue js component:

<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>

returns:

window.google_recaptcha_public_key undefined 
window.google_recaptcha_public_key2 undefined

where can I leave painless and happy all global configuration?

notice this configuration lives in my laravel backend. So I wont copy paste all values from the backend to the front end

标签: vue.js vuejs2
2条回答
萌系小妹纸
2楼-- · 2020-06-17 04:54

You should save your window variable in Vue.prototype

main.js

Vue.prototype.$authUser = window.authUser;

After that, you can access your data as follows:

Vue template

<div v-text="$authUser.name"></div>

Vue script

let name = this.$authUser.name;
查看更多
smile是对你的礼貌
3楼-- · 2020-06-17 05:06

U can use Vue.prototype in main.js file, or in file you import Vue

Vue.prototype.Hereanyname = window.hereanyname;

and in your Vue application, you can use it

Hereanyname.thefunction

Real example on Laravel

in main.js

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

new Vue({
    el: '#app',
    template: '<App/>',
    components: {App}
});

in your application

:href="Routes.route('laravel.route.here')"

So for your case

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

new Vue({
    el: '#app',
    template: '<App/>',
    components: {App}
});

inside application

mounted() {
  console.log(this.GoogleRecaptcha)
}
查看更多
登录 后发表回答