Assign a value to the <li> element and modify the prop when the user clicks using vue.js

I've been attempting to update props from child to parent using the $event in an @click event.

I sent the data and $event from the parent to the child as shown below. in the parent component:

<v-filter
    :sortTypePrice="sortTypePrice"
    :sortTypeNewest="sortTypeNewest"
    v-on:updatePrice="sortTypePrice = $event"
    v-on:updateDate="sortTypeNewest = $event"
/>


data(){
    return {
        sortTypePrice: "",
        sortTypeNewest: "",
    }
 }

computed: {
  filterArticles(){

      let filteredStates = this.api.filter((article) => {
          return (this.keyword.length === 0 || article.address.includes(this.keyword)) 
      });

      if(this.sortTypePrice == "price") {
          filteredStates = filteredStates.sort((prev, curr) => prev.price1 - curr.price1);
      }
      if(this.sortTypeNewest == 'created_at') {
          filteredStates = filteredStates.sort((prev, curr) => Date.parse(curr.created_at) - Date.parse(prev.created_at));
      }

      return filteredStates;
  },
}

I received the props and performed the $event update. However, my @click event is not functioning as expected.

in the child component:

<ul>
  <li v-model="sortPrice" @click="updatePrice" :value="price">lowest</li>
  <li v-model="sortDate" @click="updateDate" :value="created_at">newest</li>
</ul>


props:["sortTypePrice", "sortTypeNewest"],
name: "controller",
data(){
    return {
        price: "price",
        created_at: "created_at",
        sortPrice:this.sortTypePrice,
        sortDate:this.sortTypeNewest,
    };
},
methods: {
    updatePrice(e){
        this.$emit("updatePrice", e.target.value)
    },
    updateDate(e){
        this.$emit("updateDate", e.target.value)
    }
}

I believe I may be approaching this the wrong way. If so, what would be the correct approach to achieve this functionality?

Answer №1

Avoid using both :value and v-model together in your code. You may want to consider:

<ul>
  <li @click="$emit('updatePrice', 'price')" :value="price">lowest</li>
  <li @click="$emit('updateDate', 'created_at')" :value="created_at">newest</li>
</ul>

Answer №2

If you're looking for the most effective way to synchronize a prop between a parent and child component, consider the following approach:

In the parent component:

<!-- Add the `sync` modifier to ensure synchronization -->
<child :foo.sync="val" />

In the child component:

<input v-model="foo_" />

props: ['foo'],
computed: {

    // Create a local proxy for the `foo` prop
    foo_{
        // Set its value to match that of the prop
        get(){
            return this.foo
        },

        // Update the prop when the localized value is changed
        set(val){
            this.$emit('update:foo', val)
        }
    }
}

With this setup, you can interact with the foo_ prop in the child component just as you would with the original foo prop. Any changes made will update the parent's foo prop, ensuring that foo_ always mirrors foo. For instance, setting this.foo_ = 1 would result in foo being equal to 1.

This technique mirrors the behavior of Vue.js' v-model directive. For further insight, refer to the .sync Modifier documentation.

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

Make the textarea larger and bring it to the forefront when it is selected

I would like to make a textarea expand (increase its height) when it is in focus. The expanded textarea should not push the content down, but rather be displayed above other content. Currently, this is the code I am using (check out the example here): $( ...

Combining two states in the Vuex store

In my Vuex store, I have two states: notes (synced notes with the server/DB) localNotes (unsynced notes that will move to 'notes' state upon syncing) To display the notes in a list, I use a getter that merges the two objects and returns the me ...

Simulating a PubSub publish functionality

I have been trying to follow the instructions provided in this guide on mocking new Function() with Jest to mock PubSub, but unfortunately I am facing some issues. jest.mock('@google-cloud/pubsub', () => jest.fn()) ... const topic = jest.fn( ...

Tips for resolving the issue of 'no serverless pages built' during deployment of a Next.js application on Vercel

Recently, I've been encountering the same two errors while trying to deploy my NextJs app: // and will just error later on Error: No serverless pages were built. You can learn more about this error here I'm stuck and unsure of how to resolve bo ...

How come the back button does not initiate client-side navigation in a Next.js application?

In my Next.js application utilizing GraphQL to fetch articles from a server, I encountered an issue with dynamic routing when reloading the page while on an article and attempting to navigate back. The usual scenario works as expected: Index -> [slu ...

Page freezing due to JQuery scroll event

I successfully implemented a trigger that checks if an element is within the visible viewport and added it to the scroll event. While this works smoothly on some pages, I noticed that on larger pages it causes the page to freeze. In Firefox, I experienced ...

Receiving JSON dynamically (using socket.io) may result in parsing issues

I am currently working with JSON data that is correctly formatted at 100% accuracy. My issue arises when I execute the following code successfully: var data = {"datas":[{"matts":{"active":"1","status":"off"},"config":null,"adapters":[]}}]}; console.dir( ...

accessing Vue 3 application instance API from a file that is not a Vue file

With Vue 2, you could access the Vue instance Global api from .js files using the following syntax: Vue.prototype.$auth However, in Vue 3, you now have the app instance, which currently seems to only exist within the main.js file. So if, for example, I h ...

JavaScript fails to effectively validate URLs

I have implemented the following validation for URLs: jQuery.validator.addMethod("urlValidatorJS", function (value, element) { var regExp = (/^HTTP|HTTP|http(s)?:\/\/(www\.)?[A-Za-z0-9]+([\-\.]{1}[A-Za-z0-9]+)*\.[A-Za-z]{ ...

Can data sent to php via ajax be manipulated?

To restrict the number of characters a user can input in a textarea, I have implemented a character counter. // part of tinymce setup: function (ed) { ed.on('keyup', function (e) { var maxchars = <?php echo $max_chars_allowed; ?>; ...

The Material UI React Table onCellClick event is not triggering as expected when clicking on a

I am facing an issue with my react component that contains a material UI Table. I want to add an onCellClick event to each row of the table, but when I add it to each TableRow individually, the event doesn't get fired. However, if I add it to the Tabl ...

To trigger the action of any button in Ionic/Angular, I need to double-click

I am encountering an issue with an app that I developed using the Ionic framework. While the app works perfectly on Android devices, I am facing a peculiar situation on iOS. Every time I click a button in the Simulator or on an actual iOS device, I have t ...

Converting the given data into an object in JavaScript: a step-by-step guide

"[{'id': 3, 'Name': 'ABC', 'price': [955, 1032, 998, 941, 915, 952, 899]}, {'id': 4, 'Name': 'XYZ', 'id': [1016, 1015, 1014, 915, 1023, 1012, 998, 907, 952, 945, 1013, 105 ...

Navigating with NextJS to a personalized URL and managing the feedback from an external application

I'm currently in the process of developing an application that involves redirecting users to a specific URL, prompting them to open an app (with a url starting with zel:), and then sending a request back to my server. Here's the envisioned user j ...

Cannot display data in template

After successfully retrieving JSON data, I am facing trouble displaying the value in my template. It seems that something went wrong with the way I am trying to output it compared to others. My function looks like this, getUserInfo() { var service ...

Is there no body sent in the $.ajax post request?

My server is returning an error when I try to make a simple post request. It's saying that the post request has no body and all the keys have an "undefined" value. Here is the code for my post request: let alert_title = 'Alert'; let alert ...

Error Encountered: Nested textarea not supported in HTML

Below is the code I am working with. The issue lies with the <textarea>. In my form, there is a textarea. When I insert another <textarea> within the ckeditor value (HTML), the inner textarea ends up closing the parent textarea. Is there a sol ...

The mapStateToProps function is returning an undefined value

import React, { Component, Fragment } from "react"; import { connect } from "react-redux"; import { login, logout } from "./redux/actions/accounts"; import Home from "./Home"; import Login from "./Login"; class ToggleButton extends Component { render() ...

What is the process of transforming a basic JavaScript function into a TypeScript function?

As a Java developer diving into TypeScript for frontend development, I've encountered a simple JavaScript code snippet that I'd like to convert to TypeScript. The original JavaScript code is: let numbers = [123, 234, 345, 456, 567]; let names = ...

Building an HTML form to generate an array of objects by collecting form data

Hey there, I'm working on an HTML form in React that utilizes form action and FormData. However, when I extract the formData using my method, it shows a structure like this: https://i.stack.imgur.com/nzgLX.png My goal is to have an array of objects ...