Is it possible to create an instance of a variable

2019-08-07 14:41发布

问题:

My function counts the amount of characters within an input. This function is used on multiple inputs. The function keeps track of character count for each input individually. The remaining characters however are not kept track of individually and any characters into any input count towards a total. How can I display the remaining characters individually for each input within view and still keep my function modular to handle any input it's attached to it? Is it possible to have an instance of the variable for each time the method is called?

Thanks!

HTML
    <textarea 
        class="form-control" v-model="HighlightTitle" id="HighlightTitle" v-
        on:keyup="inputCheck">
    </textarea>

    <span>Character Count: {{ charactersRemaining }}</span>

    <textarea class="form-control" v-model="HighlightListing" 
              v-on:keyup="inputCheck" id="HighlightListing">
    </textarea>

    <span>Character Count: {{ charactersRemaining }}</span>     

Javascript

    inputCheck(element)  {

            var characterCount = element.target.value.length;
            var charactersRemaining = '';
            var maxCharacters = 500;

                charactersRemaining = maxCharacters - characterCount;

                this.charactersRemaining = charactersRemaining;

                    if(charactersRemaining < 0) {   
                         this.isOver500 = 1; 
                    }
                    else {
                        this.isOver500 = 0;
                    }
            },

回答1:

May I propose a component?

Vue.component("counted-textarea", {
  props:["maxCharacters", "rows", "value"],
  template: `
    <div>
      <textarea v-model='taValue' :rows='rows' @input='$emit("input", taValue)'></textarea>
      <span :class="{overMax: isOverMax}">Character Count: {{ remaining }}</span>
    </div>`,
  data(){
    return {
      taValue: this.value
    }
  },
  computed:{
    isOverMax(){
      if (!this.taValue)
        return false;

      return (this.maxCharacters - this.taValue.length) < 0
    },
    remaining(){
      if (!this.taValue)
        return this.maxCharacters;

      return this.maxCharacters - this.taValue.length
    }
  }
})

Used like this in your template:

<counted-textarea 
             :max-characters="50"
             rows="5"
             v-model="myTextValue">
</counted-textarea>

Example.