【问题标题】:Vue components on demand - [Vue warn]: Cannot find elementVue 组件按需 - [Vue 警告]:找不到元素
【发布时间】:2018-04-28 21:46:06
【问题描述】:

我正在做一个 php/laravel 项目,该项目需要在某些领域使用一些 vue 组件。目前,我的 vue 组件如下所示:

import Vue from 'vue';

import Notification from "./components/Notification.vue";

window.onload = function () {
   var main = new Vue({
      el: '#my-app',
      components: { Notification }
   });
}

但是,在我没有 #my-app 元素的页面上,我收到以下错误:

[Vue warn]: Cannot find element: #my-app 

有没有办法阻止这个警告?另一种问这个问题的方法是,有没有办法在我需要它的页面上使用我的通知组件,方法是创建一个#my-app 元素并且在我不需要的页面上完全没有#my-app 元素?

或者,如果我理解正确,我需要一个根 #my-app 元素,无论我是否使用通知组件?

【问题讨论】:

标签: javascript vue.js


【解决方案1】:

创建一个元素然后将组件安装到该元素很简单。

document.addEventListener('DOMContentLoaded', () => {
  const el = document.body.appendChild(document.createElement('notification'))
  const app = new Vue({
    el,
    render: h => h(Notification)
  })
})

【讨论】:

    【解决方案2】:

    我就是这样解决的。我只在检测到 #app 时实例化 Vue:

    //only use Vue when #app detected
    window.onload = function () {
        var app = document.getElementById('app');
        if (app) {
            const app = new Vue({
                el: '#app',
            });
        }
    };
    

    【讨论】:

      【解决方案3】:

      您可以在挂载 Vue 之前动态创建一个 id 为 my-app 的元素。

      import Vue from 'vue';
      
      import Notification from "./components/Notification.vue";
      
      var myAppElement = document.getElementById('my-app');
      
      if (!myAppElement) {
         var newMyAppElement = document.createElement('div');
         newMyAppElement.setAttribute('id', 'my-app');
      }
      
      window.onload = function () {
          var main = new Vue({
          el: '#my-app',
          components: { Notification }
      });
      

      【讨论】:

      • Eyal, ya gever, toda!
      猜你喜欢
      • 2015-06-11
      • 2017-05-15
      • 2018-08-10
      • 2018-01-04
      • 2017-08-20
      • 2021-11-19
      • 2019-05-16
      • 2017-03-12
      • 2018-02-06
      相关资源
      最近更新 更多