I'm building an app that a page has some vms, in others not. When we change from one page to another show the following warning:
[Vue warn]: Cannot find element: #element-id
How do I instantiate VMs only if there is the element on the page and avoid the error?
NOTE: I'm using Rails asset pipeline, so, all the javascript is concatenated into a single file.
In order to check if an element is present on a webpage, we make use of driver. findElements() method. As we know that driver. findElements() method returns a list of webElements located by the “By Locator” passed as parameter.
contains DOM API, you can check for the presence of any element in the page (currently in the DOM) quite easily: document. body. contains(YOUR_ELEMENT_HERE);
The $el option in Vue provides Vue with an existing HTML element to mount the Vue instance generated using the new keyword. this. $el. querySelector is used to access HTML elements and modify the element's properties.
One important feature of Vue is the ability to use components. Components are reusable Vue instances with custom HTML elements. Components can be reused as many times as you want or used in another component, making it a child component. Data, computed, watch, and methods can be used in a Vue component.
There are no issues just leaving it as is. This is just a warning that only runs when debug mode is on, so you should have it turned off in production anyway.
If you want to get rid of it, just check if the element exists before launching Vue -
if(document.getElementById("element-id")){
new Vue({...})
}
Ref: How to check if element exists in the visible DOM?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With