I am working on a spa using laravel and vue, I want to play a background music only in home page not in other pages, i have simplified my codes to make my point
this my routes.js codes
import home from './components/main.vue';
export const routes = [
{
path: '/',
component: home,
name: 'home'
},
]
this my root.vue
<template>
<div>
<navigation></navigation>
<router-view></router-view>
</div>
</template>
<script>
import navigation from './nav';
export default {
components:{
navigation
},
}
</script>
this is nav.vue
<template>
<div>
<nav>
<i class="fas fa-volume-slash" id="mute" v-if= "this.$route.name == 'home'" v-show = "mute" @click = "play"></i>
<i class="fas fa-volume-up" id="speaker" v-if= "this.$route.name === 'home'" v-show= "!mute" @click = "play"></i>
<!-- i want music i con to be seen only in home page -->
</nav>
<audio style="display: none;" id="backMusic">
<source src="uploads/audio/music.mp3" type="audio/mpeg">
</audio>
</div>
</template>
<script>
export default {
data(){
return{
mute: true,
audio2: null,
}
},
methods:{
play(){
if(this.mute){
this.audio2.play();
this.audio2.loop = true;
this.mute = false;
}else{
this.audio2.pause();
this.mute = true;
}
},
},
mounted(){
this.audio2 = document.getElementById('backMusic');
}
}
</script>
finally this app.js
Vue.component('root-view', require('./components/root.vue').default);
import {routes} from './routes.js';
const router = new VueRouter({
routes,
mode: 'history',
});
const app = new Vue({
el: '#app',
router,
store
});
when i navigate to login page music still plays! when i navigate to anywhere music still plays how can i stop there is no audio tag or javascript audio variable in other pages but still it goes on playing
thank you
p.s: i didnt know how to create jsfiddle containg 2 pages(to navigate)
I read some Q&A in stackoverflow and i finally got the answer
i just add watch to my nav.vue which includes audio
in any redirect i run this code to stop audio
nav.vue
watch:{
$route (to, from){
this.audio2.pause();
}
}