Mike Barwick
Mike Barwick

Reputation: 5367

Vue2 - Convert Vanilla ONKEYPRESS Function To Method

I'm trying to limit the amount of characters entered on a content editable div.

This works correctly...

<div onkeypress="return (this.innerText.length >= 140 ? false : true )">

However, I need to run this as a Vue method (in single file component). I'm trying to do the following, but can't get it to work:

<div @keypress="limitTextChar">

// data
props: {
    limitText: {
        type: Boolean,
        default: false
    },
    limitLength: {
        type: Number,
        default: 140
    }
}

limitTextChar(event) {
    return this.limitText && event.target.innerText.length >= this.limitLength ? false : true
}

Where am I going wrong?

JSBIN of the full component: https://jsbin.com/pezetuxecu/edit?js

Upvotes: 3

Views: 124

Answers (1)

Phil
Phil

Reputation: 165058

You'll need to call preventDefault() on the event based on your logic. For example

limitTextChar(event) {
  if (this.limitText && event.target.innerText.length >= this.limitLength) {
    event.preventDefault()
  }
}

Another thing to note is that props must be kebab-cased when used in a non-string template, ie instead of

<editable :limitText="true"...

it should be

<editable :limit-text="true"

Demo ~ https://jsfiddle.net/yo5o0vwt/

Upvotes: 2

Related Questions