1) watch
<template>
<div></div>
</template>
<script>
import { ref, watch } from 'vue';
export default {
setup() {
const message = ref('');
watch(message, (newValue, oldValue) => {
// DOM~
// API~
// state 변경
console.log('newValue: ', newValue);
console.log('oldValue: ', oldValue);
});
return {
message,
};
},
};
</script>
<style lang="scss" scoped></style>
2) multiple_source_type
<template>
<div></div>
</template>
<script>
import { reactive, ref, watch } from 'vue';
export default {
setup() {
const x = ref(0);
const y = ref(0);
const obj = reactive({
count: 0,
});
// watch(
// () => x.value + y.value,
// (sum, oldValue) => {
// console.log('sum: ', sum);
// console.log('oldValue: ', oldValue);
// },
// );
// watch([x, y], ([newX, newY]) => {
// console.log(newX, newY);
// });
console.log(typeof obj.count);
// watch(
// () => obj.count,
// (newValue, oldValue) => {
// console.log('newValue: ', newValue);
// },
// );
// watch(obj, (newValue, oldValue) => {
// console.log('newValue: ', newValue);
// console.log('oldValue: ', oldValue);
// });
const person = reactive({
name: '홍길동',
age: 30,
hobby: '운동',
obj: {
count: 0,
},
});
// watch(person, newValue => {
// console.log('newValue: ', newValue);
// });
console.log(typeof person.obj);
watch(
() => person.obj,
newValue => {
console.log('newValue: ', newValue);
},
);
return { x, y, obj, person };
},
};
</script>
<style lang="scss" scoped></style>
3) immediate
<template>
<div>
<p>{{ message }}</p>
<p>{{ reverseMessage }}</p>
</div>
</template>
<script>
import { ref, watch } from 'vue';
export default {
setup() {
const message = ref('Hello Vue3');
const reverseMessage = ref('');
const reverseFunction = () => {
console.log('즉시실행함!!!');
reverseMessage.value = message.value.split('').reverse().join('');
};
watch(message, reverseFunction);
reverseFunction();
return { message, reverseMessage };
},
};
</script>
<style lang="scss" scoped></style>
4) watcheffect
<template>
<div>
<form @submit.prevent>
<input v-model.lazy="title" type="text" placeholder="Title" />
<textarea v-model.lazy="contents" placeholder="Contents"></textarea>
<hr />
<button @click="save(title, contents)">저장</button>
</form>
</div>
</template>
<script>
import { ref, watchEffect } from 'vue';
export default {
setup() {
const title = ref('');
const contents = ref('');
const save = (title, contents) => {
console.log(`저장되었습니다. title: ${title}, contents: ${contents}`);
};
watchEffect(() => {
console.log('watchEffect');
save(title.value, contents.value);
});
return { title, contents, save };
},
};
</script>
<style lang="scss" scoped></style>
'개발이 좋아서 > Vue가 좋아서' 카테고리의 다른 글
14장 Events (0) | 2023.09.14 |
---|---|
13장 Props (0) | 2023.09.14 |
11장 양방향 바인딩(v-model) (0) | 2023.09.14 |
10장 이벤트 처리 (0) | 2023.09.13 |
9장 디렉티브 (0) | 2023.09.13 |