Created
January 2, 2022 23:24
-
-
Save ErikCH/919ab6590509fa658b6695ed2541a631 to your computer and use it in GitHub Desktop.
For YT video on watchEffect vs Watch -> https://www.youtube.com/watch?v=QkadKspKoJo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script setup> | |
import { watchEffect, ref, computed, watch } from "vue"; | |
import { useRoute } from "vue-router"; | |
const route = useRoute(); | |
const welcome = ref("Hello!"); | |
const count = ref(0); | |
const count2 = ref(0); | |
// Writes to a pre tag (Like console.log) | |
const write = ref(""); | |
// Side Effects Router Example | |
// watchEffect(() => { | |
// welcome.value = `Hello ${route.name}`; | |
// }); | |
// watch( | |
// () => route.name, | |
// values => { | |
// welcome.value = `Hello ${route.name}`; | |
// } | |
// ); | |
//#1 Watch runs lazily while watchEffect runs on init | |
// watch( | |
// () => count.value, | |
// (curr, prev) => { | |
// write.value = `Watch ran! ${count.value}`; | |
// } | |
// ); | |
// watchEffect(() => (write.value = `Watch Effect ran! ${count.value}`)); | |
//#2 Be more specific on what should trigger to re-run | |
// watch([count, count2], val => { | |
// write.value = `Watch Values Updated! ${count.value} ${count2.value}`; | |
// }); | |
//#3 See previous and current values of watched effect | |
watch([count, count2], ([curCount, curCount2], [prevCount, prevCount2]) => { | |
write.value = `Count Values: ${curCount}, ${prevCount} | |
Count2 Values: ${curCount2}, ${prevCount2}`; | |
}); | |
</script> | |
<template> | |
<main> | |
{{ welcome }} | |
<router-link to="/">Go to Home</router-link> | |
<router-link to="/route1">Go to route1</router-link> | |
<button @click="count++">count++</button> | |
<button @click="count2++">count2++</button> | |
</main> | |
<div class="counts"> | |
<h3>Count : {{ count }}</h3> | |
<h3>Count 2: {{ count2 }}</h3> | |
</div> | |
<h3>Console Log:</h3> | |
<pre> | |
{{ write }} | |
</pre> | |
<router-view></router-view> | |
</template> | |
<style> | |
pre { | |
font-size: 22px; | |
border: 1px solid blueviolet; | |
width: 500px; | |
margin: 0 auto; | |
} | |
#app { | |
font-family: Avenir, Helvetica, Arial, sans-serif; | |
-webkit-font-smoothing: antialiased; | |
-moz-osx-font-smoothing: grayscale; | |
text-align: center; | |
color: #2c3e50; | |
margin-top: 60px; | |
} | |
main { | |
border: 1px black solid; | |
width: 700px; | |
display: flex; | |
justify-content: space-around; | |
margin: auto; | |
padding: 20px; | |
} | |
.counts { | |
display: flex; | |
justify-content: center; | |
align-items: center; | |
gap: 10px; | |
} | |
</style> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment