Using Vue's computed property setter with an object as a prop

I have a new concept for an input component where different objects can be passed, displayed as CSV, and allow for text editing/validation with style changes based on validation results. Check out the code snippet I've been working on:

<div id="vue">
    <base-input :cslice="c.workspace"></base-input>
</div>

Javascript:

(function () {

  Vue.component('base-input', {
    props: ['cslice'],
    data: function () {
      return {
        colors: ['red', 'white', 'yellow', 'green', 'orange', 'purple'],
        ind: 1
      }
    },
    computed: {
      str: {
        get: function () {
          return Object.values(this.cslice).join(", ");
        },
        set: function (val) {
          if(val.indexOf('0'))
            this.ind = Math.floor(this.colors.length * Math.random());
        },
      },
      styleObj: {
        get: function () {
          return { color: this.colors[this.ind] };
        },
        set: function () {

        },
      }
    },
    template: '<div><input v-model="str" :style="styleObj" type="text"/></div>'
  });

  let vue = new Vue({
    el: '#vue',
    data: {
      c: {},
    },
    created: function () {
      this.c = Object.assign({}, this.c, {
        workspace: { width: 820, height: 440 },
      });
    },

  });

})();

Take a look at the fiddle demonstration: https://jsfiddle.net/tfoller/sz946qe2/3/

The current issue is that I can only delete the last character if the new style matches the current one, making the text practically uneditable. How can I resolve this problem to enable normal text editing in the input field?

Answer №1

When the child component uses a prop in its getter, it is necessary to send back a value with the same format in its setter using $emit:

set: function (val) {
   const arrValues = val.split(',').map(v => v.trim());
   console.log(arrValues);
   this.$emit('input', {
      width: arrValues[0],
      height: arrValues[1]
   })
},

This requires undoing some of the string formatting you had done initially to ensure the correct structure.

Listen for the input event in the parent component. You can rename your prop to value so that you can use v-model as the listener:

<base-input v-model="c.workspace"></base-input>

Migrate all color-changing functionalities into a separate method within the child component that gets triggered by any changes in the input. Here's a demo link:

Demo

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

The development of the React app will pause momentarily upon encountering a single low-severity vulnerability. To address this, you can either run `npm audit fix` to resolve it, or use `npm audit` to gain

A challenge arises while executing the command below in Visual Studio Code to develop a react app: create-react-app my-first-react-app The process halts and displays this message: found 1 low severity vulnerability run `npm audit fix` to rectify th ...

Issue with Refreshing onRowAdd in React Material Table

I am currently using Material Table to display my table data. However, when I use the onRowAdd function to add a new row, the page does not refresh properly. Instead, it reloads and gets stuck, requiring me to manually refresh again. newData => ...

Display the webpage exclusively when the application has been set with `app.use('/api')` in Express 4

Here is what I currently have: app.js ... var api = require('./routes/api'); app.use('/', api); app.use('/api', api); ./routes/api ... var router = express.Router(); router.get('/', passport.authenticate(' ...

vue Passing data to a Vue component and retrieving the selected value

Within my summary route, each nested route features a header containing a radio group. To display this header on all nested routes, I have utilized summary.vue located in the root of the pages folder and included <nuxt-child>. pages/summary.vue &l ...

What is the best way to transfer state information from a hook to be displayed in the App component in React

Is there a way to transfer the state(data) of info to the App hook, in order to showcase the properties within div elements? The function setInfo(info) saves the data intended for display on the Map hook and inspecting console.log(info) within _onClick rev ...

Insert Angular HTML tag into TypeScript

I am currently working on creating my own text editor, but I'm facing an issue. When I apply the bold style, all of the text becomes bold. How can I make it so that only the text I select becomes bold without affecting the rest of the text? Additional ...

Using Node.js with Express to seamlessly pass objects to EJS templates

I have a scenario where I am passing an object to my template and I want to display the details of that object in HTML. app.get('/', function (req, res) { var user = req.session.passport.user; if ( user != 'undefined' ){ ...

I keep encountering the same issue every time I try to execute the npm run watch command. Does anyone have any suggestions on how to fix this?

When attempting to execute the command npm run watch, I encountered an error as shown below: ERROR Failed to compile with 1 errors2:50:28 PM This dependency was not found: * vue in ./resources/js/app.js To install it, you can run: npm install --save vue ...

Choose a particular text node from the element that has been selected

Can anyone provide guidance on how to extract the text "Items Description" from the following HTML snippet using jQuery? <div class="items"> "Items Description" <ul> <li>1. One</li> <li>2. Two</li&g ...

Using an external call to trigger the revert method in jQuery UI

My draggable event setup looks like this: $(ids.label).draggable({ containment: ids.wrapper, revertDuration: 100, revert: function(event) { $(this).data("draggable").originalPosition = { top: $(this).data('origionalTo ...

Exploring Angular 10's advanced forms: delving into three levels of nested form groups combined with

Project Link: Click here to view the project In my testForm, I have 3 levels of formGroup, with the last formGroup being an array of formGroups. I am trying to enable the price field when a checkbox is clicked. I am unsure how to access the price contro ...

SignalR error: A type conversion issue has occurred where it is not possible to directly convert a task returning an object to a string

I'm encountering an issue with my C# hub class where the JavaScript code is returning a System.Threading.Tasks.Task instead of a string. I need help modifying the JavaScript method to return an actual string. Below is the hub class: public String ge ...

Error in Vue Vuelidate appearing when form is submitted with empty data property

I have been working on some basic validation for required fields and minimum length. The problem arises when I submit a network request for data insertion, the validation works perfectly fine. However, after the network call, if I try to make my text fie ...

Element not recognized: <my-company-form-extra> - have you properly registered this component?

I've been attempting to render a component using the is directive <template> <div> <v-tabs v-model="currentTab" fixed-tabs> <v-tab v-for="(item, i) in tabItems" :key="i">{{ item }} < ...

Leveraging Angular 2 and RxJs 5 beta observables to continuously stream data from a while loop

I am looking to develop a straightforward Angular 2 application that calculates prime numbers within a while loop and continuously updates the view with newly discovered values. My goal is to showcase the list of prime numbers using *ngFor in real-time, gi ...

Numerous slideshows using identical scripts

I am facing an issue with my code for multiple slideshows. Currently, it works fine for a single slideshow but when I have multiple slideshows and mouse over any of them, all the slideshows start running due to sharing the same class. However, if I try to ...

Adding a PDF generated from an HTML div to an email using Java

I am looking for a solution to convert the contents of an HTML div tag into a PDF file while preserving its associated CSS. This is essential as I will be using Java on the back-end to send emails, and I need to attach the PDF with the CSS intact when send ...

Having trouble uploading a file to Laravel using the jQuery .post method?

Here is a snippet of my HTML code: <input type="file" class="form-control" name="file-name" id="file-id"> This is the JavaScript function that is meant to send the file to an API: var file = $('input#file-id').val(); $.post('my/url/ ...

Can the top header stay fixed to the top of the screen even when scrolling down?

Code snippet: http://jsfiddle.net/R3G2K/1/ In my project, there are multiple divs with content and each div has a header. My goal is to make the last header that goes out of viewport "sticky" or fixed at the top. I have explored various solutions for thi ...

Struggling to handle JSON response in JavaScript

Upon receiving a JSON response from the Amazon API, here is how it appears: { "Result": { "Data": { "Title": "HALO 3 (XBOX 360 - REGION FREE)", "FormattedPrice": "$19.95", "Source": "Product Description", "Content": "The epi ...