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

时间:2019-01-13 07:15:37

标签: vue.js vuejs2

我有这个vue js组件:

        yourEditText.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            yourEditText.setFocusableInTouchMode(true);
            return false;
        }
    });

返回:

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

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

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

3 个答案:

答案 0 :(得分:2)

U可以在Vue.prototype文件或您main.js文件中使用import Vue

Vue.prototype.Hereanyname = window.hereanyname;

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

Hereanyname.thefunction

Laravel上的真实示例

main.js

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

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

在您的应用程序中

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

所以对于你的情况

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

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

内部应用程序

mounted() {
  console.log(this.GoogleRecaptcha)
}

答案 1 :(得分:2)

  

您应该将窗口变量保存在 Vue.prototype

main.js

Vue.prototype.$authUser = window.authUser;

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

Vue模板

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

Vue脚本

let name = this.$authUser.name;

答案 2 :(得分:1)

window 在 vuex 商店中可用。如果您需要与其他操作/突变同步改变 window 属性,这可能会有所帮助,让您有机会验证其中的内容,或者在您打算放置的变量不可用时捕获错误。

export default new Vuex.store({
  state: {
    windowFoo: window.foo,
    googleRecaptcha: window.google_recaptcha_public_key
  },
  getters: {
    windowFoo: (state) => state.windowFoo,
    googleRecaptcha: (state) => state.googleRecaptcha
  },
  actions: {
    barThenFooThenBaz({ commit }, { foo }) {
        // ... do some other required actions first
        commit("setWindowFoo", foo);
       // ... do some dependent actions next
    }
  },
  mutations: {
    setWindowFoo(state, foo) {
      state.windowFoo = foo;
    }
  }
});

然后从您的单个文件组件...

//....
computed: {
  windowFoo() {
    return this.$store.getters.windowFoo;
  },
  googleRecaptcha() {
    return this.$store.getters.googleRecaptcha;
  }
},
methods: {
  async barThenFooThenBaz(foo) {
     await this.$store.dispatch({
       type: "barThenFooThenBaz",
       foo: foo
     });
     // ... do something dependent on windowFoo being set
  }
}
//....

虽然这里的其他答案是完全可以接受的,但随着我们的项目变得越来越大,我在 main.js 中使用带有 Vue.prototype 的 Vue 实例时遇到了问题,所以我希望这会有所帮助!