vue.js 'document.getElementById' shorthand
JqueryGetelementbyidvue.jsJquery Problem Overview
Does vue.js have a shorthand for document.getElementById('#id')
like JQuery's $('#id')
?
If so, where is the reference for this in the docs so I can locate other information?
Jquery Solutions
Solution 1 - Jquery
Theres no shorthand way in vue 2.
Jeff's method seems already deprecated in vue 2.
Heres another way u can achieve your goal.
var app = new Vue({
el:'#app',
methods: {
showMyDiv() {
console.log(this.$refs.myDiv);
}
}
});
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<div id='app'>
<div id="myDiv" ref="myDiv"></div>
<button v-on:click="showMyDiv" >Show My Div</button>
</div>
Solution 2 - Jquery
You can use the directive v-el
to save an element and then use it later.
<div v-el:my-div></div>
<!-- this.$els.myDiv --->
Edit: This is deprecated in Vue 2, see 胡亚雄 answer
Solution 3 - Jquery
Try not to do DOM manipulation by referring the DOM directly, it will have lot of performance issue, also event handling becomes more tricky when we try to access DOM directly, instead use data and directives to manipulate the DOM.
This will give you more control over the manipulation, also you will be able to manage functionalities in the modular format.
Solution 4 - Jquery
If you're attempting to get an element you can use Vue.util.query
which is really just a wrapper around document.querySelector
but at 14 characters vs 22 characters (respectively) it is technically shorter. It also has some error handling in case the element you're searching for doesn't exist.
There isn't any official documentation on Vue.util
, but this is the entire source of the function:
function query(el) {
if (typeof el === 'string') {
var selector = el;
el = document.querySelector(el);
if (!el) {
({}).NODE_ENV !== 'production' && warn('Cannot find element: ' + selector);
}
}
return el;
}
Repo link: Vue.util.query
Solution 5 - Jquery
you can find your answer in the combination of these two pages in the API:
> ref is used to register a reference to an element or a child > component. The reference will be registered under the parent > component’s $refs object. If used on a plain DOM element, the > reference will be that element
> An object that holds child components that have ref registered.