[Vuejs]-Vuejs: How to allocate a function after clicking to some elements separately?

0👍

NavBar Toggle VueJs


I suggest you this method

  • i use a loop to minimize code.
  • with the v-for key attribute, i can keep on track on the current item in the loop and change his active property.
  • on click, i first deselect all items and after change the active attribute of the selected item.

=======

<template>
  <div class="hello">
    <h3>Ecosystem</h3>
    <ul>
      <li
        v-for="item in menuList"
        :key="item"
        @click.stop="
          deselectAll();
          item.active = !item.active;
        "
        :class="{ 'list-border': item.active }"
      >
        <RouterLink class="link" :to="item.to">{{ item.label }}</RouterLink>
      </li>
    </ul>
  </div>
</template>

<script>
  import RouterLink from "vue-router";

  export default {
    components: {
      RouterLink,
    },
    name: "HelloWorld",
    data: () => {
      return {
        menuList: [{
            to: "https://router.vuejs.org",
            label: "vue-router",
            active: false,
          },
          {
            to: "https://vuex.vuejs.org",
            label: "vuex",
            active: false,
          },
          {
            to: "https://github.com/vuejs/vue-devtools#vue-devtools",
            label: "vue-devtools",
            active: false,
          },
          {
            to: "https://vue-loader.vuejs.org",
            label: "vue-loader",
            active: false,
          },
          {
            to: "https://github.com/vuejs/awesome-vue",
            label: "awesome-vue",
            active: false,
          },
        ],
      };
    },
    methods: {
      deselectAll() {
        this.menuList.map((i) => (i.active = false));
      },
    },
  };
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  h3 {
    margin: 40px 0 0;
  }
  
  ul {
    list-style-type: none;
    padding: 0;
  }
  
  li {
    display: inline-block;
    margin: 0 10px;
  }
  
  a {
    color: #42b983;
  }
  
  .list-border {
    border-bottom: 4px solid red !important;
  }
</style>

You can try it here on sanbox

Leave a comment