Several functions linked to a single prop in Vue

The reference material can be found here:

https://v2.vuejs.org/v2/guide/components-custom-events.html#Customizing-Component-v-model

seems a bit confusing to me regarding how to link multiple events to the same component:

In:

https://codesandbox.io/s/dawn-dust-2tno0?file=/src/components/EditCategory.vue

is this method correct for emitting multiple events (edit/delete category) related to the same prop:

  <div
    class="modal-body"
    v-bind:taskItem="taskItem"
    @click="$emit('edit-category', $event.target.taskItem)"
  >
    <slot name="name"> Edit Name </slot>
  </div>

  <div
    class="modal-body"
    v-bind:taskItem="taskItem"
    @click="$emit('delete-category', $event.target.taskItem)"
  >
    <slot name="delete"> Delete Category </slot>
  </div>

?

Model definition is as follows:

  model: {
    prop: "taskItem",
    event: "edit-category",
  },
  props: {
    taskItem: {
      required: true,
      type: Object,
      default() {
        return {};
      },
    },
  },

The example in the documentation:

Vue.component('base-checkbox', {
  model: {
    prop: 'checked',
    event: 'change'
  },
  props: {
    checked: Boolean
  },
  template: `
    <input
      type="checkbox"
      v-bind:checked="checked"
      v-on:change="$emit('change', $event.target.checked)"
    >
  `
})

does not clearly explain how to connect more than one event per prop; like:

  model: {
    prop: 'checked',
    event: 'event-a',
    event: 'event-b',
  },

?

Answer №1

In this scenario, utilizing v-model may not be the most suitable approach.

v-model serves as a way to abstract a specific prop and define which event will trigger an update in the component's value. This setup works well for components like input fields, where the value prop (a string) triggers an input event upon updating.

However, your example with taskItem does not align with this structure. In the case of the taskItem object, there are separate actions for editing or deleting its category/name. Since you're not replacing the entire taskItem object in these actions, using v-model might not be appropriate.

Additionally, two other points to consider:

  • Applying v-bind:taskItem directly on a <div> element is invalid since <div> is not a component and does not possess a taskItem prop to bind to. Vue would likely attempt to set the taskItem attribute on the div with the stringified value of the taskItem prop, resulting in undesired behavior.
  • Your click handler within the <div> references $event.target.taskItem, which isn't valid (perhaps assuming that v-bind:taskItem would enable direct access). Given that taskItem is already available as a prop within the component's scope, you can simply use it without additional manipulation.

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

What's the issue with my jQuery AJAX script?

I am experiencing an issue with my ajax pages using jQuery to retrieve content. Only one page seems to be working properly, even though I have multiple pages set up. How can I resolve this problem? $(document).ready(function() { $('.lazy_content& ...

What is the best way to show instructions immediately upon receipt of a response?

I'm currently working on developing a website similar to ChatGpt using the OpenAI API for GPT. However, there is a delay in generating responses with GPT taking a few seconds. As a result, my code only displays the instruction once the response from G ...

Unable to Render Data URI onto HTML5 Canvas

I have been attempting for quite some time and feeling frustrated. I am facing issues with my Data URI image not being able to write to my canvas for reasons unknown .... Here's the code snippet ... function addImage() { var allfiles = $("#postAtta ...

What is the process of developing a straightforward Node.js script to encapsulate a binary or executable file?

I am looking to develop a Node.js file that can seamlessly execute an executable binary file and handle all inputs and outputs, specifically targeting Windows operating systems. Reason for this: I aim to install an executable tool via npm install -g in or ...

Adjust the size of the div to fit its content while maintaining the transition animation

I am aiming for the DIV height to automatically adjust to the text within it, while also maintaining a minimum height. However, when the user hovers their mouse over the DIV, I want the height to change smoothly without losing the transition effect. When ...

``Is it possible to adjust the style of an HTML element based on the style of another element?

Within my web application, I am dynamically changing the style of an HTML element using JavaScript. Below is the code snippet: function layout() { if(document.getElementById('sh1').getAttribute('src') == "abc.png") { docum ...

What is the best way to output information to a webpage using json_encode in PHP?

I've implemented a button on my webpage that triggers a database call using ajax, so the page can dynamically display the data without requiring a refresh. Oddly, when I click the button and inspect the source and network tab, everything seems to be f ...

Setting up AngularJS can be a pain

Greetings, my name is Rahim. While setting up AngularCLI, I ran into the following issue: 'ng' is not recognized as an internal or external command, operable program or batch file. C:\Users\ASUS ROG>ng --version 'ng' is ...

Alter the displayed content of the component based on the tab that is selected

How can I change the content of a div outside of v-tabs based on the selected tab? I want to use the tabs as a navigation bar and not contain the content within the tabs. Do I need to use v-router within the component and give each tab a different href? M ...

The JSON request was unsuccessful in sending the JSON object to PHP, resulting in an empty var_dump

I am encountering an issue where my $_POST array in PHP is empty when I try to pass a JSON object with an AJAX request on my JavaScript page. Here is the JavaScript code: function send(cat, subcat) { var type = cat.options[cat.selectedIndex].text ...

How can we stop the jumping of images in the grid? Is there a way to eliminate the jump effect?

Here is a script I am working with: <script src="http://static.tumblr.com/mviqmwg/XyYn59y3a/jquery.photoset-grid.min.js"></script> <script> $(document).ready(function() { $('.photoset-grid').photose ...

Enable the feature for users to upload images to a specific folder within the Chrome extension without the need for

I need to implement a feature in my Chrome extension that allows users to upload images directly to a specific folder named "upload" without needing a submit button. <form action="/upload"> <input type="file" name="myimages" accept="image/*"> ...

What is the process for redirecting an API response to Next.js 13?

Previously, I successfully piped the response of another API call to a Next.js API response like this: export default async function (req, res) { // prevent same site/ obfuscate original API // some logic here fetch(req.body.url).then(r => ...

Having trouble with React's useEffect and React-Query's useQuery?

As a React newbie, I'm trying to implement global error handling using a context provider and a custom hook. Main Objective: Implementing a system to handle errors at the global level. The Issue: Errors reappear immediately after being removed. I s ...

Guide on separating a variable by commas using jQuery

After making an Ajax call to a Java servlet, I am retrieving data and storing it in the 'data' variable upon success. Here is the code snippet: var s1=""; var ticks =""; $('#view').click(function(evt ...

Unable to retrieve information obtained from MongoDB

After successfully retrieving all data from the "topics" collection using find() with cursor and foreach, I am encountering an issue. When I attempt to assign the fetched information to a variable named "data" and send it back to the page, it consistently ...

finding the relative path based on a given URL

Struggling to extract a relative path from a URL. For example, from , I want to get /my/path. I attempted the following: url = 'http://test.com/my/path'; console.log(url.replace(/^(?:\/\/|[^\/]+)*/)); Unfortunately, I am only ...

Vue.js - Including new information in an array and passing it to the props (assistance needed)

I am facing an issue where I want my component to be able to add a new sidebar menu item every time the user clicks an add button. Essentially, my component should appear when the user is defining their own sidebar menu items. Here is the Vue.js code that ...

Unable to modify the value of data using the data() method

Just a basic HTML code snippet <div class="this" data-info="false"></div> $('.this').data('info'); This will correctly output: false $('.this').data('info', 'true'); data-info remains u ...

Is there a way to postpone the action so that the bot will not acknowledge the second command until after I have completed the first command

client.on('message', async (message) => { let author = message.author.username if (message.author.bot) return; if (message.content.startsWith('-queue open ')) { message.content = message.content.replace('-queue o ...