简体   繁体   中英

What is be the best way to code selecting mode as Windows using javascript?

You can select a folder in windows when you clic on a folder once..

I'm working with Vuejs. I would like to code the same thing with multiple arrays i get from my database and exposed with v-for

What i'm thinking about, is to add a new column (select) to each array with default value = 0 . Then i can apply a function on-click on each array to change it's select value to value = 1 and i can also add a css class to distinct the selected element (Blue border color).

At this moment, my element with column select value = 1 it the selected one.

It becomes more complicated when you want to change the selection (Select another array). I need first to make all columns (select) value = 0 , second, remove all css classes, before restartng the operation. (Because only one element must be selected)

Any advices? Thank you

It is pretty trivial with Vue.js. You do not need anything special like column or so. You just need to set your ViewModel correctly. Your template would be:

<div>
  <!-- Note the use of dynamic :class bindings -->
  <div v-for="folder in list" class="folder-item" :key="folder.id"
    @click="onClick(folder)"
    :class="{ 'folder-item__active': folder === selected }">
      <span>{{ folder.folderName }}</span>
  </div>
</div>

And your component's JavaScript would be:

Vue.extend({

  data() {
    return {
      // Initial list of folders
      list: [
        { folderName: 'Folder 1', id: 1 /* Some more data */ },
        { folderName: 'Folder 2', id: 1 /* Some more data */ },
      ],

      // Important to set to null for Vue.js to track reactivity
      selected: null
    };
  },

  mounted() {

    // Later on change the folder list
    setTimeout(() => {
      this.list = [/* Some new list */]
      this.selected = null;
    }, 3000);
  },

  methods: {
    onClick(selectedItem) {
      this.selected = selectedItem;
    }
  }
});

There are three things to be aware of:

  1. Use of dynamic :class bindings .
  2. Use of @click event handler to keep track of selected folder.
  3. Whenever you change list , simply change selected value to null . (Internally, comparing references to detect changes is super simple and easy.)

Of course, if your list keep changing due the use of immutable data, then your active folder selection logic will fail. In that case, you can rely of some unique identifier and update the code accordingly:

<!-- Vue binding -->
:class="{ 'folder-item__active': folder.id === selected && selected.id }"

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