sourcecode

타입 번호의 입력에 대해서, 증감 처리를 덮어쓰는 방법이 있습니까?

copyscript 2022. 8. 3. 23:10
반응형

타입 번호의 입력에 대해서, 증감 처리를 덮어쓰는 방법이 있습니까?

제가 하고 싶은 것은 내장된 html 입력 버튼을 숫자의 증감용으로 조작하는 것입니다.이것을 「방법이 있다」라고 하는 경우는, 당연히 그것이 바람직합니다.

우선 Vue를 배우기 위해 만든 작은 vue-app을 만들고 있습니다.지금 구입한 것은 Vuex 스토어입니다.이 스토어에는 쇼핑 카트의 상태와 방법이 포함되어 있습니다.이미지에 표시된 값 item.itemCount를 입력 필드 값에 바인딩했습니다.그러나 실제로 vuex-state를 적절한 방법으로 업데이트하기 위해 증가/감소 버튼이 필요합니다.

            <input
              class="slim"
              type="number"
              v-model.number="item.itemCount"
            />

입력란 사용을 중지하고 '카운트 뷰'+버튼 2개를 작성하면 되는 것은 알고 있습니다만, 이런 조작이 가능한지 궁금합니다.

쇼핑카트 업데이트표시하다

<template>
  <div class="sliding-panel">
    <span class="header">Shopping Cart</span>
    <table>
      <thead>
        <th>Item Name</th>
        <th>Count</th>
        <th>Remove</th>
      </thead>

      <transition-group name="fade">
        <tr v-for="item in items" :key="item.id">
          <td>{{ item.name }}</td>
          <td>
            <input class="slim" type="number" v-model.number="item.itemCount" />
          </td>
          <td><button @click="removeProductFromCart(item)">Remove</button></td>
        </tr>
      </transition-group>

      <tr>
        Current sum:
        {{
          sum
        }}
        of
        {{
          count
        }}
        products.
      </tr>
    </table>
  </div>
</template>

<script>
import { mapState, mapActions } from "vuex";

export default {
  computed: mapState({
    items: (state) => state.cart.items,
    count: (state) => state.cart.count,
    sum: (state) => state.cart.sum,
  }),
  methods: mapActions("cart", ["removeProductFromCart"]),
};
</script>


<style>
</style>

우선, 「증감 처리의 덮어쓰기」는 불필요합니다.이 경우,<input>따라서 모든 사용자 입력이 변경되는 값을 처리해야 합니다. 입력/해당 버튼이나 사용자 입력 값을 직접...

Vuex 상태를 업데이트하는 적절한 방법은 돌연변이를 사용하는 것입니다.그래서 기술적으로도 결속할 수 있습니다.v-modelVuex에 저장된 객체의 일부 속성(Vuex way)이 올바르지 않습니다.

값이 1개뿐인 경우 다음과 같이 계산 프로포트를 사용할 수 있습니다.

computed: {
  myValue: {
    get() { return this.$store.state.myValue },
    set(value) { this.$store.commit('changemyvalue', value )} // "changemyvalue" is defined mutation in the store
  }
}

...그리고 그것을 에 묶는다.input

<input type="number" v-model="myValue" />

그러나 값 배열로 작업하기 때문에 건너뛰는 것이 더 실용적입니다.v-model결국 완전히v-model통사당일 뿐이다:value="myValue" @input="myValue = $event.target.value"

이 경우

<input type="number" :value="item.itemCount" min="1" @input="setItemCount({ id: item.id, count: $event.target.value})"/>

...어디에setItemCount카트의 항목 수를 변경하기 위해 변환이 생성됩니다.

작업 예:

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    items: [
      { id: 1, name: 'Socks', itemCount: 2},
      { id: 2, name: 'Trousers', itemCount: 1}
    ]
  },  
  mutations: {
    setItemCount(state, { id, count }) {      
      const index = state.items.findIndex((item) => item.id === id);
      if(index > -1) {
        const item = state.items[index]
        item.itemCount = count;
        console.log(`Changing count of item '${item.name}' to ${count}`)
      }
    }
  }
})
const app = new Vue({
  store,
  template: `
  <div>
    <span>Shopping Cart</span>
    <table>
      <thead>
        <th>Item Name</th>
        <th>Count</th>
        <th>Remove</th>
      </thead>

      <transition-group name="fade">
        <tr v-for="item in items" :key="item.id">
          <td>{{ item.name }}</td>
          <td>
            <input type="number" :value="item.itemCount" min="1" @input="setItemCount({ id: item.id, count: $event.target.value})"/>
          </td>
          <td><button>Remove</button></td>
        </tr>
      </transition-group>
    </table>
  </div>
  `,
  computed: {
    ...Vuex.mapState({
      items: (state) => state.items,
    })
  },
  methods: {
    ...Vuex.mapMutations(['setItemCount'])
  }
})
app.$mount("#app")
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.12/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.5.1/vuex.min.js"></script>

<div id="app"> </div>

언급URL : https://stackoverflow.com/questions/64171295/are-there-a-way-to-overwrite-increment-decrement-handling-for-a-input-of-type-nu

반응형