itsource

라우터 파라미터에 기반한 Vue http를 사용한 데이터 가져오기

mycopycode 2022. 9. 30. 11:09
반응형

라우터 파라미터에 기반한 Vue http를 사용한 데이터 가져오기

이에 대한 해답을 찾고 vue 라우터 매뉴얼에 기재되어 있는 예에 따라 조사했지만 아직 문제가 발생하고 있습니다.컴포넌트의 초기 로드 시에 http 콜을 실행하고 라우터의 파라미터를 감시하여 vue-resource로부터의 get 콜을 갱신하려고 합니다.

내 vue 구성 요소 js는 다음과 같습니다.

export default {
  name: 'city',
  components: {
    Entry
  },
  data () {
    return {
      city: null
    }
  },
  mounted() {
    this.fetchData();
  },
  watch: {
    '$route': 'fetchData'
  },
  methods: {
    fetchData() {
      const cityName = this.$route.params.name;
      this.$http.get('http://localhost:3000/cities?short=' + cityName).then(function(response){
        this.city = response.data;
      }, function(error){
        alert(error.statusText);
      });
      console.log(cityName)
    }
  }
}

fetchData 메서드로 'cityName'을 로그아웃하면 항상 올바른 이름이 반환되지만 http get call에 해당 'cityName'을 추가하면 올바른 데이터가 반환되지 않습니다.최초 로드 시 this.city는 늘 상태로 유지되며 루트를 갱신할 때마다 데이터는 루트의 새로운 갱신 도시가 아닌 이전 선택된 도시로 반환됩니다.나는 Vue의 것을 먹어 보았다.created대신하는 재산mounted그리고 같은 일이 일어납니다.좋은 생각 있어요?

변경해 보세요.fetchDatamethod를 다음과 같이 설정합니다.

fetchData() {
  const cityName = this.$route.params.name;
  this.$http.get('http://localhost:3000/cities?short=' + cityName).then((response) => {
    this.city = response.data;
  }, (error) => {
    alert(error.statusText);
  });
  console.log(cityName)
}

=>함수의 표기법은this컴포넌트의 컨텍스트에서 사용합니다.

언급URL : https://stackoverflow.com/questions/53396748/fetch-data-using-vue-http-based-on-router-params

반응형