Vue2指令并单击“抛出未定义的对象”(TypeScript)

Vue2指令并单击“抛出未定义的对象”(TypeScript),typescript,vuejs2,Typescript,Vuejs2,我正在尝试用TypeScript在Vue2中创建一个指令,到目前为止一切都正常,直到我想要创建一个可单击的按钮 代码如下: import Vue from 'vue'; import {Component} from 'vue-property-decorator'; @Component export default class MyDirective extends Vue { private element:HTMLElement; private binding:any

我正在尝试用TypeScript在Vue2中创建一个指令,到目前为止一切都正常,直到我想要创建一个可单击的按钮

代码如下:

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

@Component
export default class MyDirective extends Vue
{
    private element:HTMLElement;
    private binding:any;

    public inserted(element:HTMLElement, binding:any):void
    {
        // core parameters
        this.element = element;
        this.binding = binding;
    }

    public onSubmit():void
    {
        console.log('submitted!');
    }
}
在HTML中,我这样称呼它

<div v-my-directive>
    <a href="" @click="onSubmit"></a>
</div>
当我将@click=onSubmit更改为@click=onSubmit时,错误有点不同

onSubmit is not a function

有什么办法可以让它工作吗?

这里有两件事导致了你的问题

您正在用@Component注释注册MyDirective,但需要用Vue注册指令。指令'my-directive',{…}

指令上的函数在该指令之外不可用。您可能需要在父组件中或在自己的自定义组件中定义onSumbit函数

这表明onSubmit实际上应该由父组件定义:

选项2:定义自定义组件并将onSubmit函数传递给该组件

<div>
    <my-component on-submit="onSubmit"></my-component>
</div>


// Pass `onSubmit` to the component
@Component({
    props: {
        onSubmit: Function
    },
    template: '<a href="" @click="onSubmit"></a>'
})
export default class MyComponent extends Vue
{

}

指令是为较低级别的访问而设计的,比如直接向DOM元素添加事件侦听器。

您的组件类是MyDirective,但您在标记中引用的是v-my-component,这在我看来并不正确,应该是v-my-directive吗?@Sly_cardinal感谢您指出这一点。是的,这只是本例中的一个打字错误,但问题仍然存在。
<div v-my-directive>
    <!--
    onSubmit defined in `my-directive` is not accessible in this location

    onSubmit function needs to be defined in the outer component that 
    has this part of the template (not the directive).
    -->
    <a href="" @click="onSubmit"></a>
</div>
<div>
    <my-component></my-component>
</div>


// Define `onSubmit` inside a component with its own template
@Component({
    template: '<a href="" @click="onSubmit"></a>'
})
export default class MyComponent extends Vue
{
    public onSubmit():void
    {
        console.log('submitted!');
    }
}
<div>
    <my-component on-submit="onSubmit"></my-component>
</div>


// Pass `onSubmit` to the component
@Component({
    props: {
        onSubmit: Function
    },
    template: '<a href="" @click="onSubmit"></a>'
})
export default class MyComponent extends Vue
{

}