簡體   English   中英

如何使@Model 和@Emit 在帶有Typescript 的VueJs 中一起工作?

[英]How I can make @Model and @Emit work together in VueJs with Typescript?

任何人都可以幫助我使用裝飾器@Model 和@Emit 嗎? 我正在嘗試更改單擊我的組件的順序並從此處使用文檔: https://github.com/kaorun343/vue-property-decorator 這是我的代碼:

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

<script lang="ts">
import Vue from "vue"; 
import { Emit, Componet, 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>

但是當我點擊按鈕時,變量“order”的值並沒有改變。 難道我做錯了什么?

是的,你是。 這里有一些問題。

  1. 你需要像這樣import { Vue, Component, Model, Emit } from 'vue-property-decorator;

  2. class 需要有一個像這樣的@Component裝飾器

@Component({/* Additional data can go in here */})
export default class MyButton extends Vue {}
  1. 這不是 vue 打算發射事件的方式。 您不能更改order的值,因為它是同一文件中的readonly屬性。 如果您將按鈕放在像這樣的另一個組件中
// 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>

並像上面那樣監聽發出的事件,然后父組件中的 order 變量會改變,但子組件不會改變。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM