Vue 3 Guide
Core
Computed properties
How to I define a computed property using the Composition API?
// just a getter
const userEmail = computed(() => {
return $store.getters.userEmail;
});
// a getter and setter
const selectedUserClientId = computed({
get: () => {
return $store.getters.selectedUserClientId;
},
set: (newVal) => {
$store.dispatch("setSelectedUserClientId", { client_id: newVal });
},
});
See:
How to type a computed property in the new composition API?
How to call setter for object in computed properties
Watchers / WatchEffect
How to I define an asynchronous watcher or watchEffect?
import { ref, watch, watchEffect } from 'vue'
import { useRoute } from 'vue-router'
export default {
setup() {
const route = useRoute()
...
// watch
watch(route, async (nv, ov) => {
const { data } = await api.get(`get-something/blah`)
console.log(data)
})
// watchEffect
const stateChanged = watchEffect(async () => {
const { data } = await api.get(`get-something/blah`)
console.log(data)
})
...
When should I use
watch
or watchEffect
?
Use watch
when …
- You want to do something with one or more specific reactive objects changes
- You need both the old value and the new value
- You need it to be called lazily
Use watchEffect
when …
- You want to do something whenever the state changes for any of your reactive objects
- You don’t care about the old value(s)
- You need it to run immediately when reactive dependencies change
See:
Vue 3 Composition API - watch and watchEffect
How to use Vue Watch and Vue watchEffect
Routes
How can I pass data between routes using
params
?
Simply add the data to your params
attribute:
<router-link :to="{ name: 'my-named-route', params: { id: 1, another_param: 'something else' } }">
Go to my page
</router-link>
See:
Vue, is there a way to pass data between routes without URL params?
Vuex
How can I watch for changes in the store’s values?
How can I watch for changes in the store’s values across browser tabs and windows?
const app = new Vue({
el: "#app",
data: {
name: "",
},
methods: {
onStorageUpdate(event) {
if (event.key === "name") {
this.name = event.newValue;
}
},
},
mounted() {
if (localStorage.name) {
this.name = localStorage.name;
}
window.addEventListener("storage", this.onStorageUpdate);
},
beforeDestroy() {
window.removeEventListener("storage", this.onStorageUpdate);
},
watch: {
name(newName) {
localStorage.name = newName;
},
},
});
See:
Reactive localStorage object across browser tabs using Vue.js
How can I store complex objects like arrays and dictionaries in localStorage?
By using JSON.stringfy(X)
when storing the data and JSON.parse(X)
when you fetch the data
Quasar
Working with q-table
How can I create grid for CRUD operations using a modal form for inserts/upserts with filtering, sorting, etc…?