프로그래밍/Js

vue3 options API 사용시 watch 사용법

소행성왕자 2023. 4. 12. 13:23

vue3 에서 options API 사용할때 watch 사용방법을 알아보도록 하겠습니다.

options API 에서는 setup() 할수 안에서 아래와 같이 watch 사용합니다.

첫번째 방법

import { useStore } from 'vuex';
export default {
...
...
setup() {
const store = useStore();
store.watch(_=>store.getters.afterLogin, _=>{
console.log(store.getters.afterLogin);
});
store.watch(_=>store.getters.ofprInfo, _=>{
console.log(store.getters.ofprInfo);
}, {deep:true});
},
mounted() {
const Table = (_=>{
// 자유변수 공간
return class {
constructor() {
}
async load() {
}
}
})();
},
}

위 방법은 watch 안에서 다른 함수로 호출이 안된다.

 

두번째 방법

import { ref } from 'vue';
import { useStore } from 'vuex';
expoirt default {
created() {
},
setup() {
},
mounted() {
this.watchStore();
},
data() {
},
methods: {
watchStore() {
this.$store.watch({
_=>this.$store.getters.afterLogin, _=>{
console.log('this.$store.getters.afterLogin');
this.$store.commit('setChartCrncy','USDKRW');
this.sendTr();
},
});
this.$store.watch({
_=>this.$store.getters.ofprInfo, _=>{
console.log(this.$store.getters.ofprInfo);
},
}, {deep:true});
},
sendTr() {
},
}
}

위 watch 는  watch 안에서 다른 함수를 호출할수 있다. this.sendTr();