Tutorial

Use Vue.js Template Niceties in JSX Components

Published on July 24, 2017
Default avatar

By Joshua Bemenderfer

Use Vue.js Template Niceties in JSX Components

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Certain people like JSX. Certain people think JSX is a way of life. I’m sure though that all parties agree that Vue.js’ templates do offer some convenient shorthand for common practices, even if they might idealistically disagree on whether or not they should exist. It is true, however, that JSX is more flexible. With flexibility though often comes verbosity. Particularly, Vue’s event modifiers and v-model don’t exist for JSX components.

Thankfully though, someone saw the need and created community plugins for both of these features, so now you can use JSX without much of the the extra cruft.

JSX v-model

While some people might take issue with v-model, others find it incredibly useful for reducing the amount of code needed to write and understand a single component. babel-plugin-jsx-v-model adds support for v-model in Vue JSX.

Installation

# Install through NPM...
npm install babel-plugin-jsx-v-model --save-dev
# ... or Yarn
yarn add babel-plugin-jsx-v-model -D

Now, add jsx-v-model to your plugins in your babel configuration.

.babelrc (partial)
...
  "plugins": ["jsx-v-model", "transform-vue-jsx"],
...

Usage

export default {
  data() {
    return {
      syncData: ''
    }
  },

  render: h => {
    return (
      <div class="component-wrapper">
        <h2>{this.syncData}</h2>
        <input type="text" v-model={this.syncData} />
      </div>
    )
  }
}

Now, it’s worth noting that this v-model implementation isn’t quite as robust as the Vue template one for now, but for most use-cases it should suffice. It sure beats having to write this every time:

export default {
  data() {
    return {
      syncData: ''
    }
  },

  render: h => {
    return (
      <div class="component-wrapper">
        <h2>{this.syncData}</h2>
        <input type="text" value={this.syncData} onInput={this.setSyncData}/>
      </div>
    )
  },

  methods: {
    setSyncData(evt) {
      this.syncData = evt.target.value
    }
  }
}

JSX Event modifiers

Event modifiers are another neat little trick Vue has that makes things just a little less verbose. (And also separates presentation logic from business logic.) babel-plugin-jsx-event-modifiers adds support for that too. (As an added bonus, this plugin works for React JSX as well.)

Now, it’s worth nothing that this doesn’t support the whole plethora of event modifiers available for Vue.js, nor does it add support for custom ones. It just implements the standard bubbling control and key modifiers.

  • :stop - Wraps the event with a function containing event.stopPropagation().

  • :prevent - Wraps the event with a function containing event.preventDefault().

  • :k[key code] Only fires the event if a matching key is pressed. (Note, this differs from the Vue implementation, which does not have the k prefix.) Only valid on key events.

  • :{key name} Only fires the event if a matching key is found (by name.)

    Valid Key Names:

    • esc
    • tab
    • enter
    • space
    • up
    • down
    • left
    • right
    • delete

Installation

# Install through NPM...
npm install babel-plugin-jsx-event-modifiers --save-dev
# ... or Yarn
yarn add babel-plugin-jsx-event-modifiers -D

Now, add jsx-event-modifiers to your plugins in your babel configuration.

.babelrc (partial)
...
  "plugins": ["jsx-event-modifiers", "transform-vue-jsx"],
...

Usage

export default {
  render: h => {
    return (
      <div class="component-wrapper">
        <button onClick:prevent={this.doSomething}>
          Do Something
        </button>

        <input type="text"
          placeholder="To do something, press enter."
          onKeyup:enter={this.doSomething}
        />
      </div>
    )
  },

  methods: {
    doSomething() {
      ...
    }
  }
}

Which, again, is a significant improvement over the alternative:

export default {
  render: h => {
    return (
      <div class="component-wrapper">
        <button onClick:prevent={evt => {
          evt.preventDefault();
          this.doSomething();
        }}>
          Do Something
        </button>

        <input type="text"
          placeholder="To do something, press enter."
          onKeyup:enter={evt => {
            if (evt.charCode === 13) {
                this.doSomething()
            }
          }}
        />
      </div>
    )
  },

  methods: {
    doSomething() {
      ...
    }
  }
}

So yeah, enjoy having some of the best parts of Vue templates in your JSX!

And I swear if any of you start grumbling about magic or non-javascriptyness

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Joshua Bemenderfer

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel