【问题标题】:How to conditionally mount root vue instance?如何有条件地挂载 root vue 实例?
【发布时间】:2020-03-22 18:28:37
【问题描述】:

有没有办法使用 vue 来检查应该挂载 vue 实例的元素是否确实存在?我遇到了此元素不存在的情况,并希望避免出现以下错误:

[Vue warn]: Cannot find element: #app
[Vue warn]: Error in created hook: "TypeError: Cannot convert undefined or null to object"
TypeError: this.$store.getters[(this.namespace...

案例是:我希望能够在挂载vue之前检查元素是否真的存在。如果没有元素,请勿尝试安装。

【问题讨论】:

  • 您的具体情况是什么? div#app 应始终在index.html 中可用。否则你可能会搞砸设置。
  • Vue 中没有特定机制,但您可以使用 document.getElementById('app') 获取元素,并且仅在该元素存在时启动 Vue。如果你不打算运行它,可能会浪费加载所有的 JS 代码。
  • 我认为你可以尝试使用 Vue 生命周期钩子,你应该特别检查 mounted。有关生命周期钩子的更多信息,您可以在此处阅读:Vue life cycle

标签: vue.js


【解决方案1】:

只需使用 vanilla JS 来检查现有标签。

const storeMounted = new Vuex.Store({
  state: {
    string: "Store mounted"
  }
})

if (document.getElementById('app')) {
  new Vue({
    el: "#app",
    store: storeMounted,
    computed: {
      string() {
        return this.$store.state.string
      }
    },
    mounted() {
      console.log('Mounted to #app')
    }
  })
}

const storeNotMounted = new Vuex.Store({
  state: {
    string: "Store not mounted"
  }
})

if (document.getElementById('noApp')) {
  new Vue({
    el: "noApp",
    store: storeNotMounted,
    mounted() {
      console.log('Mounted to #noApp')
    }
  })
}
<script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.js"></script>
<script src="https://unpkg.com/vuex@3.1.2/dist/vuex.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">{{string}}</div>

在上面的sn-p中可以看到控制台没有错误,一个Vue实例挂载在一个有合适ID的&lt;div&gt;中,另一个没有挂载.

Vue 非常有用 - 但它是“唯一的”JavaScript :D

编辑

我添加了Vuex,所以你可以看到它不会导致任何问题。

【讨论】:

  • 是的,这几乎解决了我的问题 :) 不过,我不确定 vue 部分是否应该预料到这样的事情。谢谢
  • 我很高兴能提供帮助。实际上它已经在 Vue 中了 - $mount('#app')。如果你没有在你的 Vue 实例中使用 el 属性,那么你可以随时挂载它:) stackoverflow.com/questions/46831452/… 和官方文档:vuejs.org/v2/api/#vm-mount
猜你喜欢
  • 1970-01-01
  • 2018-05-18
  • 2020-06-03
  • 1970-01-01
  • 2021-05-08
  • 2017-06-06
  • 2020-10-20
  • 2019-02-03
  • 1970-01-01
相关资源
最近更新 更多