简体   繁体   中英

How to show active state on hover/focus in two elements at the same time in Vue.js/Vuex

This is a Vue.js and Vuex related problem.

I'm building an aplication where I show a list of residences (ul -> li -> a) while at the same time showing those illustrations' position in an illustration, solved via SVG (active elements are path and polygon). If it was just the one element I could do show active state using only css, but because there are two active elements at the same time I need an event.

Previously I solved the issue by giving the residence, stored in Vuex, a hasFocus: false value, which I would change to true on mouseenter/focus and back to false on mouseout/focusout. With that I can add/remove a class has-focus to which I add the active state css. I have now redone the datastore to use Vuex ORM , after which I'm seeing worse frame rate drops when carying out the mutation.

Is there a better way of doing this than using a value in a Vuex (ORM) object model?

Some code:

In Vuex:

residences: [
{
  id: 1,
  hasFocus: false,
  […] // Other values, not relevant to this question
},
{
  id: 2,
  hasFocus: false
},
…
…
],

In ResidenceItem.vue:

<router-link
  […]
  v-bind:class="{
    'has-focus': residence.hasFocus === true,
  }"
  @mouseenter.native.stop="toggleFocus(true)"
  @mouseout.native.stop="toggleFocus(false)"
  @focus.native.stop="toggleFocus(true)"
  @focusout.native.stop="toggleFocus(false)"
  […]
>
// Content
</router-link>
[…]

props: {
  id: {
    required: true,
  },
},


methods: {
  toggleFocus(focus) {
    Residence.update({
      where: this.id,
      data: {
        hasFocus: focus,
      },
    });
  },
},

why should "hasFocus" be stored in vuex? is there a need to be? if not, you should move it to ResidenceItem.vue 's data() . i think it is a just temporary state on vue.

<router-link
  :class="{
    'has-focus': focused,
  }"
  @mouseenter.native.stop="focused = true"
  @mouseout.native.stop="focused = false"
  @focus.native.stop="focused = true"
  @focusout.native.stop="focused = false"
  […]
>
...

data() {
  return {
    focused: false,
  };
},
...

if hasFocus is needed in vuex (which i think it is a bad idea), you should use normal vuex state to store like focusedResidenceId: null .

I can provide more detail explanation if you need. Please let me know if you so.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM