任何人都可以帮助我使用装饰器 @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”的值没有改变。我做错了什么吗?
最佳答案
是的,你是。这里有一些问题。
您需要像这样导入 vue
import { Vue, Component, Model, Emit } from 'vue-property-decorator;
该类需要有一个像这样的
@Component
装饰器
@Component({/* Additional data can go in here */})
export default class MyButton extends Vue {}
- 这不是 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 变量将更改,但子组件中不会更改。
关于javascript - 如何让 @Model 和 @Emit 在 VueJs 中与 Typescript 一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58538776/