In this article we are going to list some common and useful Vue Apis and Macros that can help you in day to day coding.
computed
const count = ref(1) const plusOne = computed(() => count.value + 1) console.log(plusOne.value) // 2 plusOne.value++ // error //As a getter/setter const count = ref(1) const plusOne = computed({ get: () => count.value + 1, set: val => { count.value = val - 1 } }) plusOne.value = 1 console.log(count.value) // 0
watchEffect
const count = ref(0) watchEffect(() => console.log(count.value)) // -> logs 0 setTimeout(() => { count.value++ // -> logs 1 }, 100)
watch
The watch API is the exact equivalent of the Options API this.$watch (and the corresponding watch option). watch requires watching a specific data source and applies side effects in a separate callback function. It also is lazy by default – i.e. the callback is only called when the watched source has changed.
A watcher data source can either be a getter function that returns a value, or directly a ref:
// watching a getter const state = reactive({ count: 0 }) watch( () => state.count, (count, prevCount) => { /* ... */ } ) // directly watching a ref const count = ref(0) watch(count, (count, prevCount) => { /* ... */ })
$emit
Trigger an event on the current instance. Any additional arguments will be passed into the listener’s callback function.
<div id="emit-example-argument"> <advice-component v-on:advise="showAdvice"></advice-component> </div> const app = createApp({ methods: { showAdvice(advice) { alert(advice) } } }) app.component('advice-component', { emits: ['advise'], data() { return { adviceText: 'Some advice' } }, template: ` <div> <input type="text" v-model="adviceText"> <button v-on:click="$emit('advise', adviceText)"> Click me for sending advice </button> </div> ` }) app.mount('#emit-example-argument')