Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

vue.js - v-model not working with bootstrap datepicker

Scenario

I'm changing a themes default and super ugly datepicker and decided to use bootstraps datepicker, found here. The problem im having is that my 'v-model' attribute isnt doing anything when i use the datepicker, but its doing something when i type in the input field.

Code

// Html
<div class="position-relative has-icon-left">
    <input v-model="user.date_of_birth" placeholder="dd/mm/yyyy" id="date-of-birth" class="form-control datepicker" name="date">
    @{{ user.date_of_birth }}
</div>

// javascript
$('.datepicker').datepicker({
    format: 'dd/mm/yyyy',
    setDate: new Date()
});

the datepicker works and is initialised and it changes the value on the input field. My problem is that v-model is completely ignored unless i physically type in the field!

Question

How do i get v-model to work with this datepicker? Is there a specific reason that v-model isn't working with this datepicker?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you can use v-model like this:

<div id="app">
    <my-date-picker v-model="date"></my-date-picker>
    {{date}}
</div>


Vue.component('my-date-picker',{
    template: '<input type="text" v-datepicker class="datepicker" :value="value" @input="update($event.target.value)">',
    directives: {
        datepicker: {
            inserted (el, binding, vNode) {
                $(el).datepicker({
                    autoclose: true,
                    format: 'yyyy-mm-dd'
                }).on('changeDate',function(e){
                    vNode.context.$emit('input', e.format(0))
                })
            }
        }
    },
    props: ['value'],
    methods: {
        update (v){
            this.$emit('input', v)
        }
    }
})


var app = new Vue({
    el: '#app',
    data: {
        date: '2018-03-01'
    }
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...