vue.js 'document.getElementById' shorthand
Solution 1:
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:
You can use the directive v-el
to save an element and then use it later.
https://vuejs.org/api/#vm-els
<div v-el:my-div></div>
<!-- this.$els.myDiv --->
Edit: This is deprecated in Vue 2, see 胡亚雄 answer
Solution 3:
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:
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:
you can find your answer in the combination of these two pages in the API:
- REF
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
- vm.$refs
An object that holds child components that have ref registered.