簡體   English   中英

隨需應變的Vue組件-[Vue警告]:找不到元素

[英]Vue components on demand - [Vue warn]: Cannot find element

我正在一個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元素?

或者,如果我理解正確,那么無論我是否使用Notification組件,我都需要一個root#my-app元素?

您可以在掛載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 }
});

我通過這種方式解決了。 我僅在檢測到#app時實例化Vue:

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

創建一個元素然后將組件安裝到該元素很簡單。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM