programing

Vuejs는 변경 이벤트 시 오래된 값을 가져옵니다.

copysource 2022. 8. 11. 23:38
반응형

Vuejs는 변경 이벤트 시 오래된 값을 가져옵니다.

아래의 제 스니펫을 참조해 주세요.변경된 모델의 이전 값을 얻으려면 어떻게 해야 합니까? 이 경우 경과 시간은 vuej 단위입니다.

var app = new Vue({
  el:"#table1",
  data:{
   items:[{name:'long name One',age:21},{name:'long name Two',age:22}]
  },
  methods:{
    changeAge:function(item,event){
      alert(item.age);
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://unpkg.com/vue/dist/vue.js"></script>

<table class="table table-cart" id="table1">
   <thead>
     <tr>
       <th>Name</th>
       <th>Age</th>
     </tr>
  </thead>
   <tbody>
     <tr v-for="(item,index) in items">
       <td>{{item.name}} :</td>       
       <td>
         <input type="text" name="qty"
                v-model="item.age"   
                @change="changeAge(item,$event)">
       </td>
     </tr>
   </tbody>
 </table>

시계를 사용하려고 합니다만, 연대를 보는 데 도움이 되지 않습니다.

이 솔루션에서는 사용자 입력에서 발생하는 변경을 처리할 때만 이전 값이 필요하다고 가정합니다.일반적인 모델 변경이 아닌 경우가 대부분입니다.아래에는 필요에 따라 모든 변경을 감시하는 솔루션 개요를 추가했습니다.단, 이 컴포넌트가 아닌 장소에서 다른 변경을 제어하는 것이 좋을 수도 있습니다.

v-model수동 조작으로 대체한다.

"v-model은 기본적으로 사용자 입력 이벤트의 데이터를 업데이트하기 위한 구문설탕(...)"이기 때문에 큰 해로움 없이 이벤트를 직접 처리할 수 있습니다.

「」, 「」를 합니다.v-model:value됩니다.item.age업데이트되지만 경과시간은 자동으로 업데이트되지 않습니다.

<input type="text" name="qty"
       :value="item.age"
       @change="changeAge(item,$event)">

다음 값을 '하다'를 합니다.item.age = event.target.value로로 합니다.changeAge 이렇게요.

changeAge: function(item, event){
  alert(item.age);  // Old value
  alert(event.target.value);  // New value
  item.age = event.target.value;  // Actual assignment
}

참고: v-model에서 실제로 사용하는 @input을 대신 사용할 수 있습니다.

그게 다야, 효과가 있을 거야.변경을 방지하려면 할당을 생략하면 되지만 입력 값을 재설정해야 합니다. item.age = item.ageVue.set(item, 'age', item.age)효과가 있을지는 모르겠지만 잘 모르겠어요.

★★★★★★event.target.value하세요. 이치parseInt().

각 항목에 대해 개별 구성 요소 인스턴스를 만들고 거기에 워치를 만듭니다.

모든 변화를 지켜봐야 할 경우를 대비해서.단, 필요한 경우 이 컴포넌트가 아닌 다른 장소에서 수행해야 합니다.

것은 아직 안 되어 있기 하겠습니다.v-for 「 「」<input>그러면다른성분를 들면요.<my-item>...을 붙입니다v-model=item 위에 컴포넌트 에 '이러다', '이러다', '이러다', '이러다', '이러다', '이러다', '이러다', '이러다', '이러다'를 만듭니다<input> 할 수배송하다valueinput/change외부 이벤트컴포넌트에는 하나의 소품이 포함되어 있기 때문에 워처를 직접 연결할 수 있습니다.관련 문서: 컴포넌트 기본, 커스터마이즈 컴포넌트, 프로포츠.

여기서 설명한 것처럼 변경 시 요소의 오래된 값을 얻을 수 없습니다.또한 개체를 볼 때 개체의 참조가 변경될 때까지 여기서 설명하는 것처럼 오래된 값을 얻을 수 없습니다.

이러한 문제를 해결하려면 , 의 클론이 되는 계산 속성을 작성할 수 있습니다.items이 계산된 속성 위에 워처를 놓으면 이전 값을 알 수 있습니다. 아래 작업 코드를 참조하십시오.

var app = new Vue({
  el:"#table1",
  data:{
   items:[{name:'long name One',age:21},{name:'long name Two',age:22}]
  },
  watch:{
    clonedItems: function(newVal, oldVal){
      alert(JSON.stringify(newVal));
      alert(JSON.stringify(oldVal));
    }
  },
  computed:{
    clonedItems: function(){
       return JSON.parse(JSON.stringify(this.items))
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://unpkg.com/vue/dist/vue.js"></script>

<table class="table table-cart" id="table1">
   <thead>
     <tr>
       <th>Name</th>
       <th>Age</th>
     </tr>
  </thead>
   <tbody>
     <tr v-for="(item,index) in items">
       <td>{{item.name}} :</td>       
       <td>
         <input type="text" name="qty"
                v-model="item.age">
       </td>
     </tr>
   </tbody>
 </table>

너무 늦을 수도 있다.워치 오브젝트 내의 함수명이 워치되는 변수로 명명되어 있는 한, 이것은 나에게 효과가 있었습니다.특정 변수만 감시합니다.

watch:{
   items: function(newVal, oldVal){
      console.log("New value: "+ newVal + ", Old value: " + oldVal);
   },
   other_variable: function(newVal, oldVal){
      console.log("New value: "+ newVal + ", Old value: " + oldVal);
   }
}

v-model가치 제안으로 바꿉니다. v-model은 양방향 바인딩이므로 상태를 복잡하게 만든 다음 변경 이벤트에서 사용 기간 속성을 수동으로 수정합니다.

<input type="text" name="qty"
                :value="item.age"   
                @change="changeAge">



export default {
  change(val) {
     let ov = this.item.age
     let nv = val
     // do something
     // this.item.age = nv
   }
}

간단하게 사용할 수 있습니다.

<input type="text" name="qty" v-model="item.age" @change="changeAge($event)">

그리고.

changeAge: function(event){
  item = event.target.value;  // Actual assignment
}

vue 메서드 개체에서

https://vuejs.org/v2/api/ #Vue-nextTick

 changeAge() {
             this.$nextTick(() => {
                // here the current values are set, do desired actions
                
            })
}

저도 같은 문제가 있었어요.입력을 Vue 컴포넌트로 포장하고 래퍼 컴포넌트의 속성을 보면서 작업을 했습니다.워처에서는 $emit을 호출하여 새로운 값, 오래된 값, 아이템을 인수로 전달했습니다.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://unpkg.com/vue/dist/vue.js"></script>

<table class="table table-cart" id="table1">
    <thead>
        <tr>
            <th>Name</th>
            <th>Age</th>
        </tr>
    </thead>
    <tbody>
        <tr v-for="(item,index) in items">
            <td>{{item.name}} :</td>       
            <td>
                <item-age-input
                    :item="item"
                    @age-changed="ageChanged"></item-age-input>
            </td>
        </tr>
    </tbody>
</table>

<script>
Vue.component('item-age-input', {
    props: {
        item: {
            type: Object,
            required: true
        }
    },
    template: `<input type="text" name="qty" v-model="item.age">`,
    watch: {
        "item.age": function(newAge, oldAge) {
            this.$emit('age-changed', newAge, oldAge, this.item);
        }
    }
});

var app = new Vue({
    el:"#table1",
    data:{
        items:[{name:'long name One',age:21},{name:'long name Two',age:22}]
    },
    methods: {
        ageChanged: function(newAge, oldAge, item){
            alert(newAge + ', ' + oldAge);
            console.log(item);
        }
    }
});
</script>

언급URL : https://stackoverflow.com/questions/42197822/vuejs-get-old-value-when-on-change-event

반응형