Home > Net >  Same Vue.js component in two browser tabs make <select> mirror its selected values
Same Vue.js component in two browser tabs make <select> mirror its selected values

Time:12-15

I have a Vue app, using vue-router and a few components rendered in x-templates. In one of those markup templates I have a < select > object. When I open this page in two separate tabs in the same browser session, changed selections in one tab in that is mirrored in the other tab. I first thought it was the data and methods, but then I added a completely vanilla < select > with a few < option > in it, no bindings, data, event handlers or anything - and it behaves the same! When I select an option in one tab, it selects the same in the other. It is the same for other < select > objects in the same app.

I can't explain it. What am I missing? Do I need to maintain sessions to avoid this? If so, how?

Edit: It is now apparent to me that all objects behave the same, and are mirrored between the sessions. This has to be by-design, but how do I do to separate it with a good pattern in Vue.js?

App.js

Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history',
  base: "/",
  routes: [
    {
      path: '/',
      name: "start",
      component: Start,
    },
    {
      path: '/character/view/:guid',
      name: "character.view",
      component: ViewCharacter,
    }
  ]
})

new Vue({
  router,
  el: '#app',
  data: function() {
    return {
      baseUri: "/"
    }
  },
  computed: {
  }
})

HTML

<html>
....
<script type="text/x-template" id="template-character-sheet">
<div>
  <select>
    <option>1</option>
    <option>2</option>
  </select>
</script>
...
<script src="/components/ViewCharacter.js"></script>
<script src="/components/App.js"></script>
...
</html>

ViewCharacter.js (pieces)

const ViewCharacter = {
    template: "#template-character-sheet",
    components: {
      "navigation": Navigation
    },
    data: function() {
      return {
        properties: values,
        .......
      }
    },
    computed: {
      current_stability: function() {
        return this.rules.stability_levels.filter(o => o.level == this.character.stability)[0];
      },
      .......
    },
.......
}

CodePudding user response:

[Untested]

I think your problem is having the same :key in both of your <select>, Try adding a generated key to resolve the issue.

Docs: https://v3.vuejs.org/guide/migration/key-attribute.html

CodePudding user response:

Brain meltdown. This was me forgetting browser-sync was running in the toolchain to serve the content. Switched to serve, and the problem obviously disappeared.

  • Related