Is there a way to effectively combine @Model and @Emit in VueJs using Typescript?

I could really use some assistance with @Model and @Emit decorators. I'm attempting to alter the order on click within my component, and I referred to the documentation found here: https://github.com/kaorun343/vue-property-decorator. Below is the code snippet:

<template>
<button @click="onSortClick">Sort</button>
</template>  

<script lang="ts">
import Vue from "vue"; 
import { Emit, Component, Model } from "vue-property-decorator";

export default class MyButton extends Vue {

    @Model("sort", { type: String, default: "none" }) readonly order!: string;

    @Emit("sort")
    onSortClick() {
        const nextSortOrder = {
                ascending: "descending",
                descending: "none",
                none: "ascending"
        };
        return nextSortOrder[this.order];
    }
}
</script>

After clicking the button, however, the value of the "order" variable does not seem to change. Any insights into what might be going wrong?

Answer №1

Absolutely, you are correct. There are several issues that need to be addressed here.

  1. Make sure to import Vue correctly by using the syntax

    import { Vue, Component, Model, Emit } from 'vue-property-decorator;

  2. Your class should have a @Component decorator like this

@Component({/* Additional data can go in here */})
export default class MyButton extends Vue {}
  1. The method of emitting events in Vue is not being followed properly in this scenario. Modifying the value of order is not allowed as it is a readonly property within the same file. If you place your button in another component as shown below
// ParentFile.vue

<template>
    <my-button @sort="order = $event"></my-button>
</template>

<script lang="ts">
  import { Component, Vue, Watch } from 'vue-property-decorator';
  import MyButton from '@/components/MyButton.vue';

  @Component({
    components: {
      MyButton
    }
  })
  export default class Home extends Vue {
    order = 'Wow';

    @Watch('order')
    orderChanged(newVal: string) {
      // eslint-disable-next-line no-console
      console.log(newVal); // order will change here
    }
  }
</script>

If you follow the above setup and listen for the emitted event as described, the variable "order" in the parent component will get updated while the child component remains unchanged.

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 are the steps to create two frames using Twitter Bootstrap?

I'm just starting to work with Twitter Bootstrap and I need some help. Can someone assist me in creating a two-column layout inside the HTML, where the menu in the header stays visible even when scrolled down? I've included my HTML code below. Th ...

Looping through NavItems component using JavaScript or Angular

My Angular project includes a navbar component with an app sidebar that has a navItems attribute. Below is the content of my navBar: <app-header style="background-color : #e65100;" [fixed]="true" [navbarBrandFull]="{ src: &a ...

Retrieve both the keys and values from a deeply nested JSON object

My goal is to retrieve JSON data with a specific structure as shown below: {"Points": {"90": {"0": {"name": "John Phillip", "slug": "john"}, {"1&q ...

Updating the class of an HTML element in VueJS after it has been clicked: a step-by-step guide

Currently utilizing VueJS version 2.3.0, I am now in need of changing a HTML element's class after it has been clicked. Here is the snippet of template code I have: <template id="model-template"> <span> <button v-on:click= ...

Sending information from Vue frontend to Node/Express backend

I need to enable a user to input a city into a text field on the '/' route. Once submitted, I want to redirect to '/result' and display the information. Currently, in order to display the desired information on '/result', I ha ...

Combine two events in jQuery using the AND operator

Can I create a condition where two events are bound by an AND logic operator, requiring both to be active in order for a function to be called? Let's say you have something like this: foobar.bind("foo AND bar", barfunc); function barfunc(e) { al ...

Remove an element from an array in JavaScript when a condition is met in an if/then statement

I am currently working on a function that loops through elements in an array and removes values outside of a specific range. However, I have encountered an issue where using the pop method always removes the last element in the array rather than the intend ...

How can a service be injected in NestJs based on its interface?

I have a module named payment.module.ts with the following setup: @Module({ controllers: [PaymentController], }) export class PaymentModule {} In my payment.service.ts file, I want to utilize a service that adheres to an interface. Here is an example ...

`store and utilize the data retrieved from chrome.sync.storage.get()`

As I work on a Chrome extension, I am facing an issue with retrieving information from chrome.storage. This involves saving some data in the options page and then accessing it in the content_script. In the options.js, this is how the information is saved: ...

What could be causing the issue of images not loading in Chrome while they are loading perfectly in Mozilla when using CSS3?

Recently, I dove into a project utilizing react with webpack, and everything was smooth sailing until I encountered the CSS hurdle. Despite successfully configuring webpack, trouble brewed when it came to styling. Specifically, setting the background image ...

Leveraging dynamic actions in Oracle APEX to interact with a date field

Just starting out with oracle apex and looking for some advice. I have a form where I need to enter header information. There is a date field called P100_ENTERED_DATE, and if the value entered in this field is less than the current date, I want to enable ...

An unexpected type error occurred: Unable to read the undefined property 'map' when utilizing Highcharts

I am currently working on developing highcharts using data from Firebase. I came across a helpful example here: However, when I try to integrate it into my application, I encounter the following error: firebase.js:43 Uncaught TypeError: Cannot read pr ...

Refresh the page to change the section using vue.js

I am currently working on a website using Laravel and Vue.js. I require two separate sections for the site: Site: https://www.example.com Admin: https://www.example.com/admin Within the resource/js/app.js file, I have included the main components as fo ...

Tips for activating an HTML input field using Javascript

I am currently using localStorage to store a string input by the user as a title, which will be saved for future visits. I would like to implement a button that allows the user to delete the displayed text (from localstorage) and enables the input field fo ...

Ensuring focus remains on an element after updating data in VueJS

How come I cannot focus on this autoComplete after the v-on:changeSelect event is triggered? <auto-complete p-id="txtUf" p-title="UF" ref="comobUf" :p-service-url="rotas.rotaComboUF" v-model="endereco.uf" p-value="_id" p-label ...

Socket.io integration with JWT authentication

Having some trouble establishing a connection with JWT. It's not returning anything and I'm not very familiar with JWT so not sure where I might be going wrong. Unable to do anything on localhost:4000 due to the lack of connection. Any suggestio ...

Navigate to the logout page automatically when closing the final tab

In order to comply with the requirement, I need to log out the user when they close the last tab on the browser. ngOnInit() { let counter: any = this.cookieService.get('screenCounterCookie'); counter ? ++counter : (counter = & ...

Exploring creative solutions for generating PDFs with Node JS

Looking for a way to generate PDF Documents in Node.JS? Is there an alternative solution for organizing templates for various types of PDF creation? I've been utilizing PDFKit for creating PDF Documents on the server side with Javascript. Unfortunate ...

Encountering a loading glitch with Vue3 and pnpm while trying to open a Story

Currently facing an issue while attempting to set up Storybook with Vue3 and pnpm. The window renders, but the content keeps loading indefinitely. Here's a visual representation: https://i.sstatic.net/xaavu.png Upon running it, I encounter the follo ...

Incorporating a vuejs component within another for enhanced functionality

Within my app.js file, I have the following code: import MenuItem from './components/MenuItem.vue' import NavMenu from './components/NavMenu.vue' new Vue({ el: '#app', components: { 'nav-menu' : NavMe ...