I am trying to manage my current website using Vue and more particularly Vue Router. As I am already using Bootstrap, I need some Javascript to manage the state of my buttons. The following code only works if I comment the script section.
<template>
<div class="container">
<header class="d-flex justify-content-center py-3 border-bottom">
<ul class="nav nav-pills" id="navbar_nav">
<li class="nav-item"><router-link to="Add" type="button" class="nav-link" onclick="update_nav_bar(this);">Add</router-link></li>
<li class="nav-item"><router-link to="Edit" type="button" class="nav-link" onclick="update_nav_bar(this);">Edit</router-link></li>
</ul>
</header>
</div>
<router-view/>
</template>
<script>
let navbar_nav = document.getElementById("navbar_nav");
function update_nav_bar(elem) {
navbar_nav.getElementsByClassName("active")[0].classList.remove("active");
elem.classList.add("active");
}
</script>
If I do not comment it, I get this error:
15:10 error 'update_nav_bar' is defined but never used
So far I removed a lot of getElementById calls in my code thanks to Vue. So I guess there is a more elegant (and working...) way to achieve what I want, but I am new to Vue and lack any hindsights. Could you help ?
You have to define the function in the methods object. Or - if you use the composition-api - return the function from the setup fuction.
<script>
let navbar_nav = document.getElementById("navbar_nav");
export default {
methods: {
update_nav_bar(elem) {
navbar_nav.getElementsByClassName("active")[0].classList.remove("active");
elem.classList.add("active");
}
}
}
</script>
But maybe you should rethink the function in general. Usually you can achieve this without manipulating the DOM manually with JavaScript.