How to realize the data Synchronize of two pages by vue

for example, there are two pages of An and B, and when you want to modify the data of page A, the data of page B also changes at the same time. And when two pages are opened at the same time

I tried using Vuex, and found that after modifying the data on page A, the data on page B remained unchanged.

/ / A.vue

< template >

{{getName}}
<button @click="changeName" value=""></button>
{{getName}}

< / div >
< / template >

< script >
export default {
computed: {

getName(){
  return this.$store.state.name
}

},
methods: {

changeName () {
  this.$store.state.name = "newName"
  //this.$store.commit("updateName")
}

}
}
< / script >

/ / B.vue
< template >

{{getName}}

< / div >
< / template >

< script >
export default {
computed: {

  getName(){
  return this.$store.state.name
}

}
}
< / script >

/ / store/index.js

import Vue from "vue"
import Vuex from" vuex"
Vue.use (Vuex)

export default new Vuex.Store ({
state: {

)
name: "oldName"

},
mutations: {

updateName (state) {
  state.name = "newName"
}

}
})

Dec.29,2021

first of all, it is impossible for you to open these two pages at the same time, so there are many ways to update data. And vuex can fully meet your needs. Please post the code


the value of Vuex can not be modified directly in this way, it is recommended to learn it first. You need to use mutations to modify


does this require a resident request like socket.io? Request regularly, find the back-end data update, and then get the new data.

Menu