Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Maybe below problems of v-model has solutions, but I have not see the appropriate documentation.

  • "Chaining" the v-model: e. g. we want custom component has the v-model, and this v-model is related with child <input>'s element's v-model.
  • Using the objects (including arrays which is the particular case of ECMAScript's object) as v-model.
  • Modifying data: e. g. users inputs only digits, but the value which component emits is comma separated number (for the instance, iser's input: "4545667", emitted value: "4,545,667")

The first question in my research: what v-model can not do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
159 views
Welcome To Ask or Share your Answers For Others

1 Answer

v-model="formData" === v-bind:value="formData" v-on:input="formData = $event.target.value". It's not a magic command that does everything, but a shorter way to write a basic functionality.

To get the behaviour you need, you have to write your own components that take the value and do something with it.

To chain v-model between multiple layers of components, you want to $emit the new data rather than the default behaviour of changing the components' state. The easiest way to do this is by using a computed getter/setter. I use the code below to pass through anything from simple values to entire objects to custom input components that handle the binding to different html inputs.

--- ParentTemplate:
<Child v-model="formData"></Child>

-- ChildTemplate:
<input v-model="localValue">

-- ChildScript:
computed: {
    localValue: {
      get() {
        return this.value;
      },
      set(localValue) {
        this.$emit('input', localValue);
      },
    },
  },

If you need to convert data from an input before it's sent out (eg formatting), you can use a computed value or method to transform the data before you $emit it in the setter.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...