programing

사용자 지정 지시 VueJ에서 모델 업데이트s

goodcopy 2022. 10. 7. 21:46
반응형

사용자 지정 지시 VueJ에서 모델 업데이트s

현재 Vue를 사용하고 있습니다.JS 2.0과 커스텀 디렉티브에서 1개의 Vue 인스턴스의 모델을 갱신하고 싶은데, 그 좋은 방법을 찾고 있습니다.이는 JQueryUI-Datepicker를 구현하는 커스텀 디렉티브를 작성하려고 하기 때문입니다.코드는 다음과 같습니다.

<input type="text" v-datepicker="app.date" readonly="readonly"/>

Vue.directive('datepicker', {
  bind: function (el, binding) {
    $(el).datepicker({
      onSelect: function (date) {
        //this is executed every time i choose an date from datepicker
        //pop.app.date = date; //this work find but is not dynamic to parent and is very dirty
        Vue.set(pop, binding.expression, date); //this should work but nop
      }
    });
  },
  update: function (el, binding) {
    $(el).datepicker('setDate', binding.value);
  }
});

var pop = new Vue({
    el: '#popApp',
    data: {
        app: {
            date: ''
        }
    }
});

디렉티브에서 pop.app.date를 다이내믹하게 갱신하는 방법을 알고 있는 사람이 있습니다.이 예에서는 binding.expression return이 datepicker에서 선택한 현재 날짜를 반환하지만 디렉티브에서 모델을 갱신하는 방법은 모릅니다.

이렇게 하면 효과가 있습니다.

// vnode (third argument is required).
bind: function (el, binding, vnode) {
    $(el).datepicker({
        onSelect: function (date) {
            // Set value on the binding expression.
            // Here we set the date (see last argument).
            (function set(obj, str, val) {
                str = str.split('.');
                while (str.length > 1) {
                    obj = obj[str.shift()];
                }
                return obj[str.shift()] = val;
             })(vnode.context, binding.expression, date);
         }
    });
},

참고 자료: https://stackoverflow.com/a/10934946/2938326

@Kamal Khan의 답변에 대한 후속 조치입니다(매우 효과적입니다).

방금 아래와 같이 실시했습니다.이렇게 하면 개체 찾기가 제거되고 Vue의 설정 기능에 의존하여 값을 설정할 수 있습니다.

bind: function (el, binding, vnode) {
    $(el).datepicker({
        onSelect: function (date) {
             Vue.set(vnode.context, binding.expression, date);
         }
    });
},

저의 완전한 지시는 다음과 같습니다.

  Vue.directive("datepicker",{
    bind(el,binding, vnode) {
       console.log(binding);
       var self = el
      $(self).datepicker({
        dateFormat:'mm-dd-yy',
        onSelect: function (date) {
            Vue.set(vnode.context, binding.expression, date);
        }
    });      
    },
    updated: function (el,binding) {
    }
 });  

다음으로 템플릿 또는 html에서 호출할 수 있습니다.

 <input v-model="dtime" v-datepicker="dtime"> 

dtime을 데이터 모델 값으로 지정합니다.

이것이 나를 미치게 만들었기 때문에 다른 누군가에게 도움이 되기를 바란다.

언급URL : https://stackoverflow.com/questions/40009197/update-model-from-custom-directive-vuejs

반응형