简体   繁体   中英

v-model input binding remove string after it has a space Vue.js

I want to delete part of a string when a space is added using v-model input binding. For example I have the following Vue setup:

<template>
  <input v-model="customerName" placeholder="edit me">
  <p>Message is: {{ customerName }}</p>
</template>

<script>
export default {
  name: 'conversation-app',
  data () {
    return {
      customerName: '',
    }
  },
}
</script>

The input value will be names such as 'Peter Parker', 'Bob Marley' etc.

I'd like the v-model data to be converted to the first name only when it is printed out into:

<p>Message is: {{ customerName }}</p>

Make a computed property called firstName that returns a segment of the customerName containing the letters before the first space:

computed: {
  firstName() {
    return this.customerName.split(' ')[0];
  }
}

Then use that in your template instead:

<p>Message is: {{ firstName }}</p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM