Created computed getter and setter for Vue models (also known as "props") using the syntax of Vue Class Component

After exploring the limitations of v-model in Vue 2.x in this Stack Overflow thread, I discovered a way to connect parent and child components using v-model. The solution proposed is as follows:

--- ParentTemplate:
<Child v-model="formData"></Child>

-- ChildTemplate:
<input v-model="localValue">

-- ChildScript:
computed: {
    localValue: {
      get() {
        return this.value;
      },
      set(localValue) {
        this.$emit('input', localValue);
      },
    },
  },

I attempted to rewrite this solution using the vue-class-component syntax, but faced challenges. The code snippet below highlights the issue:

export default class TextEditor extends Vue {

  @Prop({ type: String, required: true }) private readonly value!: string;


  private get localValue(): string {
    return this.value;
  }

  private set localValue(newValue: string) {
    this.$emit("input", newValue);
  }
}

The solution provided for writing computed setters in class-based components in vuejs does not apply here due to the read-only nature of component properties. Therefore, directly modifying this.value is not possible.

Issue with Direct value Usage

<EditorImplementation 
  :value="value" 
  @input="(value) => { onInput(value) }" 
/>
@Component({
  components {
    EditorImplementation: CK_Editor.component
  }
})
export default class TextEditor extends Vue {

  @Prop({ type: String, required: true }) private readonly value!: string;


  @Emit("input")
  private onInput(value: string): void {
    console.log("checkpoint");
    console.log(this.value);
  }
}

Let's assume the initial value is an empty string.

  1. Input "f"
  2. Log will show "checkpoint" ""
  3. Input "a"
  4. Log will show "checkpoint" "f"
  5. Input "d"
  6. Log will show "checkpoint" "fa"

And so forth.

Answer №1

It appears that you are currently receiving an input value from the parent, modifying it, and then sending it back to the parent. This approach may not be optimal.

Consider implementing the following:

In your EditorImplementation component:

 <input
  ....
  :value="value"
  @input="$emit('input', $event.target.value)"
 />
 
@Prop({default: ''}) readonly value!: string

Next Steps:

<EditorImplementation 
  v-model="localValue"
  @input="(value) => { onInput(value) }" 
/>

Ensure to import this into your Text Editor file as shown below:

@Component({
  components {
    EditorImplementation: CK_Editor.component
  }
})
export default class TextEditor extends Vue {
  private localValue = '';

  @Emit("input")
  private onInput(value: string): void {
 
  }
}

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

Recursive types in TypeScript allow for the definition of types that

Is there a way to implement the function below without utilizing any? Playground type MyType = { name: string, age: number, score: { prime: number, }, prize: { first: { discount: number } } } export const trim = ( myObj: ...

Learn the process of seamlessly uploading various document formats, videos, and previewing documents with Angular software

I am having trouble viewing uploaded files in the carousel. While I can see video and image files, other document formats are not displaying. Can someone please recommend a solution to enable viewing all types of documents as well? mydata = [] onSelect ...

Using VueJS to dynamically insert API data into a text field

After retrieving text from an API, I need to customize it by injecting or substituting variables before displaying it. To better understand what I mean, please check out the example below: https://jsfiddle.net/0q4ot5sw/ new Vu ...

Locating the CSS selector for Material-UI combobox options in Playwright

Currently, I am struggling to identify the CSS selector for the items listed under a mui Combobox. The main issue is that each item is dynamically identified by the 'aria-activedescendant' attribute, which takes on values like id-option-0, id-opt ...

Creating a dynamic components binder

Currently, I am utilizing Vue version 2.7 with Composition API and encountering a challenge. My goal is to dynamically render a component based on a reactive value. Below is the code snippet: const renderTab = ref('admin'); // later in the templa ...

String defines the type

I came across the following code snippet in some external sources that I intend to incorporate into my project: const INIT: 'jsonforms/INIT' = 'jsonforms/INIT' Can someone explain what it means to define a type with a string like INIT ...

What is the process for implementing a splash screen in VueJS?

Having trouble creating a splash screen (loading-screen) in Vue JS that fades away after a few seconds to reveal the default view? I've experimented with several approaches, but none seem to be working for me. The closest example I found is on CodePen ...

Tips for overcoming indentation issues using ESLint?

Ever since I started using Vue 3 with ESlint, I've been encountering a new problem. Whenever I try to run my code, I am bombarded with numerous errors like: --fix option.</p> I'm looking for ways to disable this troublesome feature of ESl ...

Exchange information between two components (independent of parent-child relationship)

Element 1 getData(){ this.$root.$emit('event'); console.log("emitted") }, Element 2 mounted() { this.$root.$on('event', () = { alert("Triggered"); } } I am attempting to trigger "Triggered" from element 2 u ...

Tips for circumventing the use of responsive tables in Buefy

I am facing a challenge with displaying data in a Buefy table in a way that it appears as a conventional table with columns arranged horizontally on all devices, rather than the stacked cards layout on mobile. In order to accommodate the content appropriat ...

It is not possible to include external JavaScript in a Vue.js web page

Trying to integrate a Google Translate widget onto my webpage has been a bit challenging. Initially, when I added it to a normal webpage, it worked smoothly using the following code: <div class="google_translate" id="google_translate_element"></d ...

Extending an interface in TypeScript does not permit the overriding of properties

While working with Typescript, I encountered an issue where I couldn't make a property not required when overwriting it. I have defined two interfaces: interface IField { label: string; model: string; placeholder? ...

"Regardless of the circumstances, the ionic/angular service.subscribe event

Currently, while developing the login section of my Ionic app, I am encountering an issue with the getTokenAsObservable.subscribe() function. The main problem is that the function checks the token status when it is saved (by clicking the Login button) or ...

There was a problem with the WebSocket handshake: the response header value for 'Sec-WebSocket-Protocol' did not match any of the values sent

I've encountered an issue with my React project that involves streaming live video through a WebSocket. Whenever the camera firmware is updated, I face an error in establishing the WebSocket connection. Here's how I initiate the WebSocket: wsRe ...

Is there a way to prevent QtLinguist from opening every time Visual Studio tries to display a TypeScript file?

Ever since I installed Qt tools for Visual Studio, my Ctrl+click on a class name triggers Qt Linguist: https://i.stack.imgur.com/USAH1.png This hinders me from checking type definitions, even though Visual Studio has already parsed them. The type informa ...

Preserve final variable state - Angular

My function looks like this: flag: boolean = false; some_function(){ var foo = some_num_value; var bar = foo; // Storing value in a separate variable if(this.flag){ v ...

Access previous value in Vuejs onchange event

In the code snippet below, how can I retrieve the previous value of the model that has been changed, specifically the age in vuejs? var app = new Vue({ el:"#table1", data:{ items:[{name:'long name One',age:21},{name:'long name Two&a ...

On MacOS, VSCode encounters an issue with updating TypeScript imports when files are moved

I recently started transitioning a project from a mixed JS/TS setup to fully TypeScript. The project's server is hosted on AWS Lambda, and I have a tsconfig file at the root level as well as one in the /lambdas directory. One issue I've encounte ...

The functionality of the Vert.x event bus client is limited in Angular 7 when not used within a constructor

I have been attempting to integrate the vertx-eventbus-client.js 3.8.3 into my Angular web project with some success. Initially, the following code worked perfectly: declare const EventBus: any; @Injectable({ providedIn: 'root' }) export cl ...

Compiling TypeScript to JavaScript with Deno

Currently experimenting with Deno projects and looking for a way to transpile TypeScript into JavaScript to execute in the browser (given that TS is not supported directly). In my previous experience with NodeJS, I relied on installing the tsc compiler via ...