1. 程式人生 > >Vue元件使用v-model

Vue元件使用v-model

先看下簡單的,在一個頁面中使用 v-model 進行 雙向資料繫結


<input type="text" v-model="textValue">
<h1>{{ textValue }}</h1>

相信這行程式碼,大家肯定都非常熟悉!官方文件說明了 v-model 其實如如下原理:

<input type="text"
  v-bind:value = "textValue"
  v-on:input = "textValue = $event.target.value"
>
<h1>{{ textValue }}</h1>

元件上使用v-model:

//父元件 templateParant.vue

<template>
  <div>
    <template-child v-model="textValue"></template-child>

    <!-- <template-child
      v-bind:value = "textValue"
      v-on:input = "textValue = $event"
    ></template-child> -->

    <!--  這兩種寫法是等價的,至於 v-on:input = "textValue = $event" 
為什麼是 $event而不是$event.target.value,這是一個值得思考的問題 -->
    <div>{{ textValue }}</div>
  </div>
</template>
<script>
import templateChild from './templateChild '

export default {
  
  data() {
    return {
      textValue: ''
    }
  },
  components: {
    modelChild
  },
  mounted() {
    
  }
};
</script>
<style scoped>
</style>

//  子元件templateChild.vue

<template>
  <div>
    輸入<input type="text"  
      v-bind:value="value"
      v-on:input="$emit('input',$event.target.value)"
    >
  </div>
</template>
<script>
export default {
  props: ['value'],    //子元件用一個props接住父元件傳進來的value屬性值,然後在自己的input繫結該值,並且使用$emit向父元件通訊,傳遞input事件和input輸入的值($event.target.value),在父元件v-model既可以實現與子元件的雙向資料綁定了。
  data() {},
  components: {

  },
  mounted() {
    
  }
};
</script>
<style scoped>
</style>