[英]How to bind v-model in VueJS component
我是 Vue 的新手,所以我嘗試使用Vuetify
創建一個Input Date Picker
。
這是我的代碼:
問題是,當我在選擇器中選擇日期時,控制台中出現錯誤:
[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: '$value'
這是創建該組件的正確方法嗎?
正如錯誤所述,您無法更改孩子的道具。 這是因為 Vue 使用了這個父子流:
使用這種結構,您可以確保父數據是唯一的事實來源。 為了更改數據,您需要將其發送給父級。 你的例子中幾乎有它。 您需要為v-model
發出input
以同步更改,而不是發出change
事件。
當您看到文檔中的示例時,這一點會更加清楚:
<input v-model="searchText">
確實是一樣的:
<input
v-bind:value="searchText"
v-on:input="searchText = $event.target.value"
>
但是,從 vue 2.3.0 開始,您現在可以通過.sync
修飾符對 props 進行更改
Vue.component('date-picker', { props: ['label'], data: () => ({ date: null, dateFormatted: null, open: false }), created() { this.date = this.$value; }, methods: { formatDate (date) { if (!date) return null const [year, month, day] = date.split('-') return `${day}/${month}/${year}` }, parseDate (date) { if (!date) return null const [day, month, year] = date.split('/') return `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}` }, update() { this.$emit('input', this.dateFormatted); } }, watch: { date (val) { this.dateFormatted = this.formatDate(this.date) }, dateFormatted(val) { this.update(); } }, template:` <v-menu ref="open" :close-on-content-click="false" v-model="open" :nudge-right="40" lazy transition="scale-transition" offset-y full-width > <v-text-field slot="activator" v-model="dateFormatted" :label="label" placeholder="dia/mês/ano" @blur="date = parseDate(dateFormatted)" ></v-text-field> <v-date-picker v-model="date" no-title @input="open = false"></v-date-picker> </v-menu> ` }); Vue.config.productionTip = false; Vue.config.devtools=false new Vue({ el: '#app', data: () => ({ myDate: '2018-09-01' }) });
<link href="https://cdn.jsdelivr.net/npm/vuetify@1.1.4/dist/vuetify.min.css" rel="stylesheet"/> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/vuetify/1.2.0/vuetify.min.js"></script> <div id="app"> <v-app> <v-flex xs24> <date-picker label="Select a date" v-model="myDate"></date-picker> <br> Current date: {{myDate}} </v-flex> </v-app> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.