使用 v-model 雙向數據來綁定客製組件

v-model 基本概念

v-model 作用於表單元件上時,是 雙向數據綁定 的語法

<input v-model="searchText"> 
# 等於下面表示式: v-bind="searchText" 以及 @input="searchText = $event.target.value" 
<input 
  v-bind:value="searchText" 
  v-on:input="searchText = $event.target.value" 
>

客製一個基本的輸入, 若是需要在組件使用 v-model 語法,組件需要設定 prop自定義事件 $emit

Vue.component('custom-input', {
  props: ['value'],
  template: `
    <input
      v-bind:value="value"
      v-on:input="$emit('input', $event.target.value)"
    >
  `
})

HTML 使用方式

<custom-input v-model="searchText"></custom-input>

進階用法: 客製日期選擇組件

<template>
  <v-menu
    ref="menu"
    v-model="menu"
    :close-on-content-click="false"
    :return-value.sync="dateValue"
    transition="scale-transition"
    offset-y
    min-width="290px"
  >
    <template v-slot:activator="{ on, attrs }">
      <v-text-field
        v-model="dateValue"
        :label="dateLabel"
        readonly
        v-bind="attrs"
        v-on="on"
        clearable
      ></v-text-field>
    </template>
    <v-date-picker v-model="dateValue" no-title scrollable>
      <v-spacer></v-spacer>
      <v-btn text color="primary" @click="menu = false">Cancel</v-btn>
      <v-btn text color="primary" @click="confirm" >OK</v-btn>
    </v-date-picker>
  </v-menu>
</template>

<script>
import moment from 'moment-timezone'
export default {
  props: {
    date: [String, Number],
    value: [String, Number],
    label: String,
    returnNumber: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      menu: false,
      dateValue: null,
      dateLabel: null
    }
  },
  created () {
    
    if (this.label) this.dateLabel = this.label

    if ( typeof this.date === 'number') {
      this.dateValue = moment(this.date).format('YYYY-MM-DD')      
    } else {
      if (this.date) this.dateValue = this.date
    }
    
  },
  methods: {
    confirm () {
      this.$refs.menu.save(this.dateValue)
      if ( this.returnNumber ) {
        this.$emit('input', moment(this.dateValue).valueOf())
      } else {
        this.$emit('input', this.dateValue)
      }
      
    }
  }
}
</script>

HTML使用客製日期選擇組件

<template>
<v-row>
  <v-col cols="12" sm="6" md="4">
    <m-date-picker v-model="editedItem.activeDate" label="Active Date" :date="editedItem.activeDate" />
  </v-col>
</v-row>
</template>
<script>
import MDatePicker from '@/components/common/MDatePicker.vue'
export default {
  data() {
    return {
      editedItem: {}
    }
  }
}
</script>

可以搭配 Vuejs 資料異動後如何刷新當前頁面(vue-router reload),當輸入表單取消時,日期可以顯示原來的日期。

參考:

Using v-model on Components

Vue component 上該如何使用 v-model

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *