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

Is it possible to create an <h1> heading that can be clicked like a button and actually do something when clicked?

I am currently designing a web page that includes <div class="cane-wrap"> <h1 class="mc">christmas tic tac toe</h1> </div> located at the top center of the webpage, with autoplay running in the backgroun ...

How can I show a loading screen while making a synchronous AJAX call in Chrome?

Is there any method to show a loading screen in Chrome while using async:false in an AJAX call? The use of setTimeout poses several challenges when making multiple synchronous AJAX calls within the setTimeout function. Additionally, the loading indicator ...

How can the .pre() middleware function in Mongoose be utilized?

I'm curious about the use cases for mongoose .pre('validate') and .pre('save'). I understand their functionality, but I'm struggling to think of specific scenarios where I would need to utilize them. Can't all necessary a ...

Perform the action: insert a new item into an array belonging to a model

Here is the structure of my model: var userSchema = new mongoose.Schema( { userName: {type: String, required: true}, firstName: {type: String}, lastName: {type: String}, password: {type: String, required: true}, ...

What sets Fetch Promise apart in terms of delivery success?

Struggling with using strapi in my project, as the fetch function returns a promise instead of JSON data This is my code : const [products, setProducts] = useState([]); useEffect(() => { (async () => { try { l ...

What causes AJAX to disrupt plugins?

I am facing a challenge with my webpage that utilizes AJAX calls to load content dynamically. Unfortunately, some plugins are encountering issues when loaded asynchronously through AJAX. I have attempted to reload the JavaScript files associated with the ...

Saving information in binary format to a file

I have a script for setting up an installation. This specific script is designed to access a website where users can input values and upload a certificate for HTTPS. However, the outcome seems to be different from the expected input file. Below is the cod ...

Automatically trigger a popup box to appear following an AJAX request

I am currently working on a time counter script that triggers a code execution through ajax upon completion. The result of the code should be displayed in a popup box. Below is the code snippet I am using: var ticker = function() { counter--; var t = ...

JavaScript - issue with event relatedTarget not functioning properly when using onClick

I encountered an issue while using event.relatedTarget for onClick events, as it gives an error, but surprisingly works fine for onMouseout. Below is the code snippet causing the problem: <html> <head> <style type="text/css"> ...

How to implement a cyclic item generation feature in React.js

My function is meant to draw multiple items in a cycle, but it is only drawing the first item when I attempt to draw 5. This is my function: export default function CinemaHole() { const items = []; for(let i = 0; i < 5; i++) { item ...

Issues concerning date and time manipulation - Library Moment.js

As a beginner in JavaScript, I've been working on an activity that generates a table of train times based on user input. However, I'm facing issues with formatting the arrival time correctly. Whenever I input the arrival time in military format ( ...

Display a preview image at the conclusion of a YouTube video

I am currently working on an iOS device and have a Youtube video thumbnail that, when clicked, disappears and the video automatically plays in fullscreen mode using an iframe. It's working perfectly. Now, I would like to know how I can make the thumb ...

Identify all elements that include the designated text within an SVG element

I want to target all elements that have a specific text within an SVG tag. For example, you can use the following code snippet: [...document.querySelectorAll("*")].filter(e => e.childNodes && [...e.childNodes].find(n => n.nodeValue ...

What is the best way to transfer attribute values from multiple elements and paste them each into a separate element?

I have multiple elements with the tag <a class="banner2">. Each of these elements has a different URL for the background image and href value. <a href="#" target="_blank" class="banner2" style="background-image:url('<?php echo get_templat ...

Incorporating a Favicon into your NextJs App routing system

Encountering an issue with the new Next.js App Router. The head.js files have been removed, thus according to the documentation I need to implement metadata in layout.ts. My favicon file is named favicon.png. How should I specify it within the following c ...

Chaining promises: The benefits of attaching an error handler during Promise creation versus appending it to a variable containing a promise

function generatePromise() { return new Promise((resolve, reject) => { setTimeout(reject, 2000, new Error('fail')); }); } const promise1 = generatePromise(); promise1.catch(() => { // Do nothing }); promise1 .then( ...

React Native: struggling to fetch the most up-to-date information from an array

I'm working on a chat application that functions similar to a chatbot. Since I don't want to use a database and the messages are temporary, I opted to utilize JavaScript arrays. Whenever a user inputs a message in the TextInput and hits the butto ...

Is it feasible to commit an object on Vue X through Actions?

I have a question regarding Vue X and actions (with commit). Can an object be passed as input in Commit? Similar to: ... action{ ResetLoginStats({commit}){ commit({ 'SetMutation1':false, 'SetMutation2':true, &a ...

Utilizing socket.io to access the session object in an express application

While utilizing socket.io with express and incorporating express session along with express-socket.io-session, I am encountering difficulty in accessing the properties of the express session within the socket.io session object, and vice versa. const serve ...

A glitch in showcasing the hello world example in Node.js with express

I've been diving into learning node.js and I'm eager to use the express framework. However, I hit a roadblock when trying to run a simple "hello world" example from the expressjs.com website. Instead of seeing the expected output, I encountered a ...