全局Vue对象未定义

时间:2020-03-05 03:16:07

标签: vue.js vuejs2

首先,我想在其他组件上重用我的验证器,因此我将其写在 myValidator.js 上。 我将Vue对象设置为window。因为我需要在 myValidator.js 上使用i18n。我得到了这个未定义的消息。但是我的其他组件却可以正常工作。我需要你的帮助。谢谢。

Uncaught TypeError: Cannot read property '$t' of undefined
    at Object../src/myValidator.js (VM406 app.js:156668)
    at __webpack_require__ (VM406 app.js:724)
    at fn (VM406 app.js:101)
    at Object../node_modules/cache-loader/dist/cjs.js?!./node_modules/@vue/cli-plugin-babel/node_modules/babel-loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/components/HeaderSearch/index.vue?vue&type=script&lang=js& (VM406 app.js:4187)
    at __webpack_require__ (VM406 app.js:724)
    at fn (VM406 app.js:101)
    at Module../src/components/HeaderSearch/index.vue?vue&type=script&lang=js& (VM406 app.js:157451)
    at __webpack_require__ (VM406 app.js:724)
    at fn (VM406 app.js:101)
    at Module../src/components/HeaderSearch/index.vue (VM406 app.js:157394)

main.js

var vm = new Vue({
  el: '#app',
  data() {
    return {
      bus: eventBus
    }
  },
  router,
  store,
  i18n,
  render: h => h(App)
})
window.vm = vm

myValidator.js

export const accountValidatorRule = [{
  required: true,
  message: window.vm.$t('valid.accountBlank'), <-- this $t is undefined
  trigger: 'change'
}, {
  min: 6,
  max: 16,
  message: window.vm.$t('valid.accountRule')
}]

侧边栏/Index.vue

<template>
  <div>
    <search ...> <-- this line
  </div>
</template>
<script>
import Search from '@/components/HeaderSearch'
...

export default {
  name: 'Index',
  components: { Logo, Search, Menu },
...
</script>

HeaderSearch / Index.vue

<script>
import * as myValidator from '@/myValidator'  <-- this line

export default {
  name: 'Index',
  data() {
    return {
      rules: {
        search: myValidator.accountValidatorRule <-- this line
      },
...
}

1 个答案:

答案 0 :(得分:0)

原因是因为在安装应用后 window.vm仅设置为vm

因此, HeaderSearch / Index.vue data()的声明是在安装该应用之前完成的。

为此,最优雅的解决方案是您在评论中找到的解决方案,我真的支持这样做:https://github.com/kazupon/vue-i18n/issues/149#issuecomment-357455921

但是,如果您想确保并使用vue生命周期,则可以尝试保留旧代码,而可以在 HeaderSearch / index.vue

中执行此操作
<script>
import * as myValidator from '@/myValidator'  <-- this line

export default {
  name: 'Index',
  data() {
    return {
      rules: {
        search: null <-- assign to nothing first
      },
mounted() {
  // update it after mounted:
    this.rules.search = myValidator.accountValidatorRule <--- the window.vm should be ready now     
}
...
}