preface
Vue-router switching is different from traditional page switching. Switching between routes is really just switching between components, not really switching between pages. This can also lead to the problem of referring to the same component and causing that component to be unable to update, which is the problem of the page being unable to update.
The problem presented
Parent component, click the div of class=item to jump to the page of the corresponding point
<template>
<div class="nav">
<div class="item"
v-for="(item, index) in dirList"
:key="index"
@click="clickItem(item)"
:style="'backgroundImage: url('+ item.bg_img +')'">
</div>
<router-view></router-view>
</div>
</template>
<script>
export default {
data () {
return {
dirList: []
}
},
methods: {
clickItem (item) {
const URL = {
name: `new${item.type}`,
params: {part: item.id, fromFlag: this.$route.name}
}
this.$router.push(URL)
}
}
}
</script>
Copy the code
Subcomponent, a page of music player, music after the end of the next page
<template>
<div class="audio">
<audio ref="audio" :src="voiceUrl"></audio>
</div>
</template>
<script>
export default {
data () {
return {
dirList: []
}
},
mounted () {
this.initAudio()
},
methods: {
initAudio () {
const audio = this.$refs.audio
audio.addEventListener('ended', () => {
console.log(That's the end of the audio.)
this.nextPage()
}, false)},nextPage () {
this.$router.push({name: `new${this.nextPageInfo.type}`, params: {part: this.nextPageInfo.id}})
}
}
}
</script>
Copy the code
Routing Settings,
{path: '/Chapter/:id',
name: 'Chapter',
component: Chapter,
children: [
{path: 'newNormal/:part', name: 'newNormal', component: newNormal},
{path: 'newReading/:part', name: 'newReading', component: newReading},
{path: 'newListening/:part', name: 'newListening', component: newListening},
{path: 'newExplain/:part', name: 'newExplain', component: newExplain}
]},
Copy the code
If the nextPage route jumps from name: ‘newNormal’ to name: ‘newNormal’, and only part changes, the page will not be updated, and vue-Router will default that you have not jumped to the new page.
The solution
Add :key=”key” to the parent component and add a random number or timestamp to the key
<template>
<div class="nav">
<div class="item"
v-for="(item, index) in dirList"
:key="index"
@click="clickItem(item)"
:style="'backgroundImage: url('+ item.bg_img +')'">
</div>
<router-view :key="key"></router-view>
</div>
</template>
<script>
export default {
data () {
return {
dirList: []
}
},
computed: {
key () {
return this.$route.path + Math.random()
}
},
methods: {
clickItem (item) {
const URL = {
name: `new${item.type}`,
params: {part: item.id, fromFlag: this.$route.name}
}
this.$router.push(URL)
}
}
}
</script>
Copy the code
The route will be updated. But that means you need to bind each one to a key value. If I jump from newNormal to newReading, I don’t have to worry about component updates.