作用

  • v-model 指令本质上是一个语法糖,可以在表单 、元素上创建双向数据绑定,它会根据控件类型自动选取正确的方法来更新元素。
    • <input v-model="value" /> 等同于

<input :value="value" $input="value= $event.target.value" /><br />

类型

input

  • <input v-model="message" >
  • <p>Message is: {{ message }}<p>

    textarea

  • <textarea v-model="message" ></textarea>

  • <p style="white-space: pre-line;">{{ message }}</p>

    单选

    1. <label>
    2. one
    3. <input type="radio" value="One" v-model="picked">
    4. </label>
    5. new Vue({
    6. data: {
    7. picked: ''
    8. }
    9. })

    多选

    1. <label>
    2. Jack
    3. <input type="checkbox" value="Jack" v-model="checkedNames">
    4. </label>
    5. <label>
    6. John
    7. <input type="checkbox" value="John" v-model="checkedNames">
    8. </label>
    9. new Vue({
    10. data: {
    11. checkedNames: []
    12. }
    13. })

    选择框

    1. <select v-model="selected">
    2. <option v-for="option in options" :value="option.value" key="option.value">
    3. {{ option.text }}
    4. </option>
    5. </select>
    6. <span>Selected: {{ selected }}</span>
    7. new Vue({
    8. el: '...',
    9. data: {
    10. selected: 'A',
    11. options: [
    12. { text: 'One', value: 'A' },
    13. { text: 'Two', value: 'B' },
    14. { text: 'Three', value: 'C' }
    15. ]
    16. }
    17. })

    form 表单

    1. <form @submit.prevent="onSubmit">
    2. <input type="text" v-model="user.name">
    3. <input type="password" v-model="user.password">
    4. <button type="submit"></button>
    5. </form>
    6. <script>
    7. export default {
    8. data(){
    9. return { user:{name:"",password:""} }
    10. }
    11. methods:{
    12. onSubmit(){ console.log(this.user) }
    13. }
    14. }
    15. </script>

    自定义组件的 v - model

    1. //MyInput.vue
    2. <template>
    3. <div>
    4. <input :value="value" @input="$emit("input", $event.target.value);" /> //触发 input 事件
    5. </div>
    6. </template>
    7. <script>
    8. export default {
    9. props: { //接受外部属性
    10. value: {
    11. type: String,
    12. },
    13. },
    14. };
    15. </script>
    16. //App.vue
    17. import MyInput from './MyInput.vue'
    18. <template>
    19. <div>
    20. {{value}}
    21. <MyInput v-model:value />
    22. </div>
    23. </template>
    24. <script>
    25. export default {
    26. data(){
    27. return {value:''}
    28. }
    29. }
    30. </script>

    修饰符

    .lazy

  • change 事件触发后将输入框的值与数据进行同步

    .number

  • 自动将用户的输入值转为数值类型

    .trim

  • 自动过滤用户输入的首尾空白字符