`V-model` default on a component called` value` will use prop (properties) and events named input, but like radio buttons, check boxes and other types of input controls might `value` properties for different purposes. At this time we can define the components of time by setting `model` option can be used to implement a different approach.
When creating components, add `model` property, which contains two properties to be configured, namely:
- event: When will trigger v-model behavior
- prop: the definition of the variables passed to the v-model, which is bound to the property value
Here is the code to achieve the effect of the counter:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdn.jsdelivr.net/npm/vue"></script> <title>vue自定义组件v-model</title> </head> <body> <div id="app"> <Stepper v-model="goodsCount"></Stepper> </div> <script> Vue.component('Stepper', { props: ['count'], template: ` <div> <button @click="sub">-</button> <span>{{count}}</span> <button @click="add">+</button> </div> `, model: { // Event: When will trigger v-model behavior Event: ' Change-COUNT ' , // define the variable passed to the v-model, which is bound to the property value prop: ' COUNT ' }, methods: { sub() { // trigger trigger names defined in the above model // no need to modify this value this.count, as long as the end result to pass out on the line the this $ EMIT. ( " Change-COUNT " , the this .count - 1 ) }, add() { this.$emit("change-count", this.count + 1) } } }) new view ({ el: "#app", data: { goodsCount: 0 } }) </script> </body> </html>