List of sortable components

I have successfully implemented a filters section using vue.js to display dynamic responses based on user-selected filters. The components, in this case, represent cars with attributes such as price and brand.

Now, I want to add two more filters that will allow me to sort the cars by a specific field, such as price. I have read that it is easy to sort lists by specifying a field and order...

Could someone guide me on how to create this sortable list for the cars?

Here is a simple fiddle I created, where I would like to sort the cars by price when the filter is clicked.

var Car = Vue.extend({

    template: '#template_box_car',
    props: {

        show: {
        default: true
        },

        code: {
        default: ""
        },

        prize: {
        default: 0
        },

        description: {
        default: "No comment"
        }
    }
});
//register component
Vue.component('box_car',Car);

//create a root instance
var vm = new Vue({
    el: 'body',

    methods: {

        sortBy: function(field, order){

        }
   }
});

Answer №1

To begin, save the information for each car part in a data property within the main component:

data: function () {
  return {
    cars: [
      { code: '11A', price: 5.00, description: 'Ford Ka' },
      { code: '11B', price: 3.00, description: 'Kia ceed' },
      { code: '11C', price: 6.00, description: 'Ford Ka' },
      { code: '13A', price: 45.00, description: 'Mercedes A' },
      { code: '17B', price: 20.00, description: 'Seat Leon' },
    ]
  }
},

Next, utilize the v-for directive to generate a box_car component for each object in the cars data property:

// In older versions of Vue.js, the code would resemble this:
<box_car 
  v-for="car in cars" 
  :code="car.code" 
  :price="car.price" 
  :description="car.description"   
  :track-by="code"
></box_car>

// For newer versions of Vue.js, you can use the `v-bind` directive to pass each object
// so there's no need to set each property explicitly:
<box_car v-for="car in cars" v-bind="car" :key="car.code"></box_car>

Then, within your sortBy method, simply arrange the cars array:

// I used lodash for sorting, but you're free to use any sorting method you prefer:
methods: {    
  sortBy: function(field, order) {
    this.cars = _.orderBy(this.cars, field, order);
  }
}

Here is a functional JSFiddle example.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Changing the appearance of a website by switching CSS stylesheets according to the size of the browser

Trying to build two versions of my website: one for mobile devices or small browsing windows, and another for large browser windows. Looking to link HTML to different style sheets based on browser size. Current attempt in code only addresses total screen ...

Stop the closure of confirmation box by disabling the space key

I've been working on a website that features a table for users to interact with. Within one column of the table, there are input boxes where users can write notes. Below each input box, there is a save button to store the entered notes in a database. ...

Ways to repurpose an S3 image

Using the carrier wave gem in Ruby on Rails and Vue.js, I successfully uploaded images to S3. Now, I am looking for a way to reuse those uploaded images as a file. Unfortunately, I am unsure of how to accomplish this. More specifically, I have a model ...

Windowing box inside a container box

I am looking to implement scrolling for just the "chat-messages" div within the "chat-bar" div on my site. I want only this specific section to be scrollable, while the rest of the site remains stationary. Currently, I have to scroll through the entire pag ...

Navigating Errors within Nested Promises: A Clear Perspective

Struggling with my first node.js backend, I am currently refactoring the login function. However, I seem to be missing something crucial when it comes to promise chaining and error handling. If anyone could help me identify where I'm going wrong, I wo ...

What could be the reason for the Laravel middleware CORS not functioning properly in conjunction with Vue

Currently, I am working with Laravel 5.7 as the backend and Vue.js as the frontend. To send HTTP requests from Vue to the Laravel backend, I decided to use the Laravel CORS package, which can be found at this GitHub link: https://github.com/barryvdh/larave ...

Steps for highlighting specific character(s) within a textarea

I am working on a program to search for specific characters within a designated <textarea> element. I want to be able to highlight or color the characters that match the search criteria within the text area. How can I achieve this effect and color th ...

Is there a way to modify AJAX response HTML and seamlessly proceed with replacement using jQuery?

I am working on an AJAX function that retrieves new HTML content and updates the form data in response.html. However, there is a specific attribute that needs to be modified before the replacement can occur. Despite my best efforts, I have been struggling ...

ThreeJs is known for effortlessly handling an abundance of vertices, far surpassing the number typically found

I came across this code snippet: function loadObject(filePath){ var loader = new THREE.OBJLoader(); loader.load( filePath, function ( object ) { child = object.children[0]; var geometry = new THREE.Geometry().fromBufferGeometry( ch ...

The Chrome application does not retain cookies

Why is the cookie url_user not being stored? Below is the content of index.html: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial- ...

Using more than one variable for filtering in Vue.js

I've been busy working on implementing table filtering in Vue.js. So far, I have successfully filtered the table by name and date. However, I'm now facing a challenge with adding another filter along with them. If you want to check out my curren ...

The response is dispatched without delay and does not necessitate awaiting

I am facing an issue with waiting for the completion of the getAllData function before proceeding further. let _partnerToken; async function getAllData(dealerId,id){ let partnerToken; var options = { 'method': 'GET', ' ...

Customize the asset path location in Webpack

I am currently working on a Vue application that utilizes Webpack for code minimization. Is there a method to dissect the chunks and adjust the base path from which webpack retrieves the assets? For example, by default webpack fetches assets from "/js" o ...

How can I place a div using pixel positioning while still allowing it to occupy space as if it were absolutely positioned?

I successfully created an slds path element with multiple steps. I want to display additional subtext information below each current step, but there might not always be subtext for every step. To achieve this, I created an absolute positioned div containi ...

The required component could not be located: @/services/AuthenticationService

Need help with using AuthenticationService in a Vue.js component This dependency could not be located: * @/services/AuthenticationService in ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/components/ ...

Getting the value returned by http.request in an app.get method using express.js

When attempting to deliver data from an API on another domain using app.get, I am able to write the data to the console successfully. However, the data is not showing up on the page ('~/restresults'). This is the current code I have: app.get(&a ...

jQuery Ajax Redirect Form

I am currently developing an HTML application with a form. Upon clicking the submit button, I initiate a server-side call using jquery.ajax(). However, when the server returns an exception, such as a Status Code 500, I need to display an error message on t ...

Transfer information from the ajax success event to an external else/if statement

I am encountering an issue when trying to transfer the appropriate result from my ajax success function to an external function for further use. Currently, I am using user input to query a data source via ajax and receiving the object successfully. The re ...

What are the steps to integrate the extract text plugin with Vue component CSS?

After successfully adding the extract text plugin to extract sass and scss for vue components, I am now interested in learning how to incorporate the extract text plugin for regular css as well. ...

Explaining the defineAsyncComponent Method in Vue 3

Recently, I've been exploring the vue3-beta release and stumbled upon a new feature called defineAsyncComponent. Surprisingly, there's not much information about it online. I'm curious about its use-case and when it should be used. How does ...