If you have developed front-end Javascript for some time, you are probably familiar with jQuery. You may even not imagine a project without it. It’s time to get rid of your old habits, you do not need jQuery anymore.
At the beginning of your Vue journey, you will eventually be thinking “I could do that sooo easily with jQuery”. That is true, but there is always another way !
Access the DOM
You know how easy it is to hide/show an element with v-show
so I won’t go down that road. But how can we access the DOM elements now ?
With jQuery you can write var myElement = $('#my-element')
. I admit, that is really cool, and it handles fancy CSS selectors. But then you are not writing vanilla Javascript anymore, and your variable doesn’t contain a DOM element, but a jQuery object, with all its API that you probably won’t need.
You could access this element using document.getElementById('my-element')
but that would not be suitable for Vue’s virtual DOM mechanism because this element could be re-rendered any time.
Fortunately, Vue provides an API to access a certain DOM element. Your HTML would look like this :
<template>
<div>
...
<p ref="myElement">This is the content of my element.</p>
...
</div>
</template>
<script>
export default {
mounted () {
console.log(this.$refs.myElement)
}
}
</script>
Read more about it in the docs
Helper functions
I know, the $.each
function was neat to iterate through an array… But now there is ES2015 and tons of helper libraries you can include, such as lodash
.
Let’s use the following array :
var myArray = ['we', 'love', 'javascript'];
And update it so that all its values become uppercase :
// jQuery
$.each(myArray, function(value, index) {
myArray[index] = value.toUppercase();
});
// ES2015
myArray.forEach((value, index) => {
myArray[index] = value.toUppercase()
})
// ES2015 (using map method)
myArray = myArray.map(value => value.toUppercase())
// lodash
var _ = require('lodash');
myArray = _.map(myArray, function(value) {
return value.toUppercase();
});
Something else in mind ?
You have another use case where you believe you need jQuery ? Let’s discuss it in the comments :)