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

stop playing audio when navigating to another pages, vue.js

我正在使用 laravel 和 vue 开发水疗中心,我只想在主页而不是其他页面播放背景音乐,我简化了我的代码来表达我的观点

这是我的 routes.js 代码

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

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

这是我的root.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:我不知道如何创建包含 2 个页面的 jsfiddle(导航)

我在Whosebug上看了一些问答,终于得到了答案

我只是将手表添加到我的 nav.vue,其中包括音频

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

nav.vue

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