Methods | Computed | Watch |
Use with event binding OR data binding | Use with data binding | Not used directly in template |
Data binding: Method is executed for every “re-render” cycle of the component | Computed properties are only re-evaluated if one of their “used values” changed | Allows you ro run any code in reaction to some changed data (e.g. send Http request etc.) |
Use for events or data that really needs to be re-evaluated all the time | Use for data that depends on other data | Use for any non-data update you want to make |
아래는 그 예시이다.
result가 37이 되는 기준으로 그 결과를 다르게 하는 코드를 작성한다.
또한 37이 되면 5초 이후에 0으로 설정되도록 한다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vue Basics</title>
<link
rel="stylesheet"
/>
<link rel="stylesheet" href="styles.css" />
<script src="app.js" defer></script>
</head>
<body>
<header>
<h1>Reactivity in Action</h1>
</header>
<section id="assignment">
<button @click="add(5)">Add 5</button>
<button @click="add(1)">Add 1</button>
<!-- 1) Connect the buttons and calculate a value (a number) -->
<!-- Show "Not there yet" until you reach a result of exactly 37 -->
<!-- Show "Too much!" if the result is greater than 37 -->
<p> Result: {{ result }} </p>
<!-- 2) Watch for changes in "result" and reset the value to 0 after 5 seconds -->
</section>
</body>
</html>
const app = Vue.createApp({
data() {
return {
counter: 0,
message: "Net there yet"
}
},
watch: {
result() {
const that = this;
setTimeout(function() {
that.counter = 0;
}, 5000)
}
},
computed: {
result() {
if( this.counter > 37 ) {
return this.counter + " is Too Much";
} else if (this.counter === 37) {
return this.counter;
} else {
return this.counter + " is Net there yet";
}
}
},
methods: {
add( num ) {
this.counter += num;
},
},
});
app.mount('#assignment')
'WEB Developer > Vue JS' 카테고리의 다른 글
v-bind 사용 - Dynamic Styling (Click 시 색상 변화) (0) | 2024.03.30 |
---|---|
08. v-bind and v-on shorthands (0) | 2024.03.30 |
07. Watcher (0) | 2024.03.30 |
06. Computed Properties (0) | 2024.03.30 |
05. USING-THE-NATIVE-EVENT: v-model (0) | 2024.03.30 |