导航到其他页面vue.js时停止播放音频

问题描述

我正在使用laravel和vue制作水疗中心,我只想在主页上播放背景音乐,而不能在其他页面上播放,我简化了代码以表达自己的观点

这是我的route.js代码

import home from './components/main.vue';
export const routes = [

    {
        path: '/',component: home,name: 'home'
    },]

这是我的根。vue

<template>
    <div>
        <navigation></navigation>
        <router-view></router-view>
    </div>
</template>

<script>
import navigation from './nav';
export default {
      components:{
  navigation
},}
</script>

这是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>

最后这个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
});

当我导航到登录页面时,音乐仍在播放!当我导航到音乐仍在播放的任何地方 我怎么停 其他页面上没有音频标签或javascript音频变量,但仍可以继续播放

谢谢

p.s:我不知道如何创建jsfiddle包含2页(进行导航)

解决方法

我阅读了stackoverflow中的一些问答,终于得到了答案

我只是将手表添加到包含音频的nav.vue

在任何重定向中,我都运行此代码以停止音频

nav.vue

 watch:{
        $route (to,from){
            this.audio2.pause();
         }
 }