【问题标题】:How I can make @Model and @Emit work together in VueJs with Typescript?如何使 @Model 和 @Emit 在带有 Typescript 的 VueJs 中一起工作?
【发布时间】:2020-02-20 15:22:45
【问题描述】:

谁能帮我处理@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”的值并没有改变。我是不是做错了什么?

【问题讨论】:

  • 更多信息在这里会有帮助吗?你想在同一个组件中捕获一个发射事件吗?还是在父组件中?

标签: javascript typescript vue.js javascript-decorators


【解决方案1】:

是的,你是。这里有一些问题。

  1. 需要像这样导入vueimport { Vue, Component, Model, Emit } from 'vue-property-decorator;

  2. 类需要有这样的@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 变量会改变,但子组件不会改变。

【讨论】:

    猜你喜欢
    • 2021-12-30
    • 1970-01-01
    • 2013-10-14
    • 2017-11-26
    • 1970-01-01
    • 2019-01-31
    • 2020-04-16
    • 2020-04-03
    • 2019-09-26
    相关资源
    最近更新 更多