[Vuejs]-Sort/filter content with javascript

0👍

Mixing Vue and jQuery like this is going to make things much, much, much more difficult than they need to be. The problem you ran into with your first filter was because Vue didn’t know about the DOM modifications your javascript filter was doing, so overwrote them on its next update. You’re going to have exactly the same problem with the jQuery filter, if you get it working.

So don’t do that.

Right now you’re letting Vue draw a full list of items, then trying to crawl through the DOM after the fact adding data attributes and hiding the elements you want filtered out. This is a lot of extra work (for both you and the browser), and will fail whenever Vue does a redraw (because it will blow away the changes you made externally.)

Instead, put the attributes in the data you’re feeding to Vue, and let Vue filter it before it draws the DOM. Which is a thing that is pretty simple to do in Vue.

(You had mentioned the need for multiple categories per project; here’s a quick example of a computed property for that:

data: {
    currentFilter: 'photo',  // set this from a route param, or a v-model, or whatever
    projects: [
        {name: "Project one", categories: ['photo', 'book']},
        {name: "Project two", categories: ['website']},
        {name: "Project 3", categories: ['photo']}
        // ...
    ]
},
computed: {
   filteredProjects() {
      return this.projects.filter(project => {
          return project.categories.indexOf(this.currentFilter) > -1
      })
   }
}

Have your template v-for over filteredProjects instead of projects, and you’re done. Whenever data.currentFilter changes, the list will redraw, filtered by the new value, automatically.)

It’s possible to use jQuery from within Vue, but it requires a pretty good understanding of what the framework is doing so you don’t wind up creating conflicts between it and your external code. (And I’ve yet to find a case where it wasn’t simpler to just rewrite the jQuery thing as a Vue component anyway.) The same is true of other modern frameworks like React or Angular; these all work on a very different model than the DOM-first strategy jQuery tends to fall back on. Especially when learning, you’ll have a much easier time of it if you stick to just one framework at a time instead of trying to mix things together.

Leave a comment