programing

VueJ가 어레이 길이 변경에 응답하지 않습니까?

goodjava 2022. 11. 30. 21:15

VueJ가 어레이 길이 변경에 응답하지 않습니까?

단일 파일 템플릿을 사용하여 배열이 비어 있으면 "여기를 클릭"을 표시하고, 채워지면 값을 표시하는 버튼을 원합니다.Ajax는 정상적으로 동작하고 있으며 오브젝트는 업데이트되고 있지만 버튼이 다시 렌더링되지 않습니다.내가 여기서 뭘 잘못하고 있는 거지?

<template>
  <span>
    <button
      v-if="value.app_token.length"
      class="btn btn-outline-primary btn-sm"
      disabled
    >Mobile App Token: {{ value.app_token[0].token }}</button>
    <button v-else class="btn btn-primary btn-sm" @click="getToken">Click to get Mobile App Token</button>
  </span>
</template>

<script>
module.exports = {
  props: ["value"],

  methods: {
    getToken() {
      axios
        .get("/patients/getToken/" + this.value.id)
        .then(response =>
          this.value.app_token.splice(
            0,
            this.value.app_token.length,
            response.data
          )
        )
        .catch(error => console.log(error));
    }
  }
};
</script>

getTokenmethod가 변환된 경우valueprop. 이는 허용되지 않습니다(콘솔에 오류가 있을 수 있습니다).

솔루션

가져온 데이터를 저장할 토큰 및 변수를 만듭니다.

data() {
  return {
    fetched: null
  }
},
computed: {
  token() {
    let token = JSON.parse(JSON.stringify(this.value.app_token));
    if (this.fetched) {
      // Now this mutates a copy, not the original
      token.splice(0, token.length, this.fetched);
    }
    return token;  
  }
}

아무것도 가져오지 않은 경우 토큰 값은 프로펠러와 동일합니다.그렇지 않으면 변경된 토큰으로 재계산됩니다.변경하다getToken데이터 결과를 저장하기 위한 방법fetched:

methods: {
  getToken() {
    axios
      .get("/patients/getToken/" + this.value.id)
      .then(response => this.fetched = response.data)
      .catch(error => console.log(error));
  }
}

이제 에서 계산한 것을 사용합니다.v-if:

v-if="token.length"

그리고 다음과 같이 표시합니다.

{{ token[0].token }}

여기 데모가 있습니다.

또한 토큰 프롭이 복잡한 객체의 일부가 아닌 토큰 문자열 그 자체일 뿐이고, 그 다음 공리도 전달한다면 훨씬 덜 혼란스러울 것입니다.id다른 소품으로서.

조건을 다음과 같이 변경하다

v-if="value.app_token && value.app_token.length >0"

이 경우,value.app_token빈 배열에, 그러면 길이가 있을 것이다.0그 때문에 상황이 바뀌게 될 것이다.true.

소품 대신 Vue 데이터를 사용해야 합니다. 컴포넌트 자체의 소품 변경은 패턴 방지입니다.매뉴얼은http://https://vuejs.org/v2/guide/components.html 를 참조해 주세요.

언급URL : https://stackoverflow.com/questions/61038176/vuejs-not-responding-to-change-in-array-length