Vue Watch

YEZI🎐·2022년 11월 22일
0

Vue

목록 보기
11/45

Watch

  • 데이터 변경에 반응하여 실행됨
  • 비동기식 또는 시간이 많이 수용되는 조작을 수행하려는 경우 가장 유용함
<div id="watch-example">
  <p>
    yes/no 질무을 물어보세요 :
    <input v-model="question">
  </p>
  <p>{{ answer }}</p>
</div>
var watchExampleVM = new Vue({
  el: '#watch-example',
  data: {
    question: '',
    answer: '질문을 하기 전까지는 대답할 수 없습니다.'
  },
  watch: {
    // 질문이 변경될 때 마다 question() 실행
    question: function (newQuestion, oldQuestion) {
      this.answer = 'Waiting for you to stop typing...'
      this.debouncedGetAnswer()
    }
  },
  created: function () {
    // 5초 마다 getAnswer() 실행
    this.debouncedGetAnswer = _.debounce(this.getAnswer, 500)
  },
  methods: {
    getAnswer: function () {
      if (this.question.indexOf('?') === -1) {
        this.answer = '질문에는 일반적으로 물음표가 포함됩니다 ;-)'
        return
      }
      this.answer = '생각 중...'
      var vm = this
      axios.get('https://yesno.wtf/api')
        .then(function (response) {
          vm.answer = _.capitalize(response.data.answer)
        })
        .catch(function (error) {
          vm.answer = 'Error! API 요청에 오류가 있습니다. ' + error
        })
    }
  }
})

위 같은 경우 비동기 연산(API 엑세스)를 수행하고, 연산의 수행 횟수를 제한하고
최종 응답을 얻을 때까지 중간 상태를 설정할 수 있다.
(computed는 불가능)

Computed vs Watched

<div id="demo">{{ fullName }}</div>
// computed
var vm = new Vue({
  el: '#demo',
  data: {
    firstName: 'Foo',
    lastName: 'Bar'
  },
  computed: {
    fullName: function () {
      return this.firstName + ' ' + this.lastName
    }
  }
})

// watch
var vm = new Vue({
  el: '#demo',
  data: {
    firstName: 'Foo',
    lastName: 'Bar',
    fullName: 'Foo Bar'
  },
  watch: {
    firstName: function (val) {
      this.fullName = val + ' ' + this.lastName
    },
    lastName: function (val) {
      this.fullName = this.firstName + ' ' + val
    }
  }
})

Computed

  • 계산해야 하는 목표 데이터를 정의하는 방식으로 소프트웨어 공학에서 얘기하는 '선언형 프로그래밍' 방식
  • 다른 데이터 기반으로 변경할 필요가 있는 데이터의 경우, watch 보다 computed 속성을 사용하는 것이 더 좋음

Watched

  • 감시할 데이터를 지정하고, 해당 데이터가 바뀌면 함수를 실행하라는 방식으로 소프트웨어 공학에서 이야기하는 '명령형 프로그래밍' 방식
profile
까먹지마도토도토잠보🐘

0개의 댓글