Skip to content

Instantly share code, notes, and snippets.

@danvega
Last active March 27, 2022 22:33
Show Gist options
  • Save danvega/5b68ed1fa383cd4a0507b018868f7574 to your computer and use it in GitHub Desktop.
Save danvega/5b68ed1fa383cd4a0507b018868f7574 to your computer and use it in GitHub Desktop.
Reactive Object Vue
<template>
<h1>User Details</h1>
<p><strong>ID:</strong>{{user.id}}</p>
<p><strong>Name:</strong>{{user.name}}</p>
<p><strong>Username:</strong>{{user.username}}</p>
<p><strong>Email:</strong>{{user.email}}</p>
<select v-model="selectedId">
<option v-for="n in 10" :key="n">{{n}}</option>
</select>
&nbsp;
<button @click="loadUser">Load User</button>
</template>
<script>
import { reactive,ref } from 'vue'
export default {
name: 'App',
setup() {
const selectedId = ref(1);
const user = reactive({
id: null,
name: '',
username: '',
email: ''
})
function loadUser() {
fetch(`https://jsonplaceholder.typicode.com/users/${selectedId.value}`)
.then((response) => response.json())
.then((data) => {
// the following will not work because vue has setup user to be a reactive object by creating getters and
// setters for each property in the ojbect. By setting user to data (if user was defined using let) results in
// the reactive object being overwritten by a plain JavaScript Object. Log data to the console to inspect it.
// user = data;
// you have to call the setter for each property you want to assign
for(const [key,value] of Object.entries(data) ) {
if(key in user) {
user[key] = value;
}
}
})
}
return {selectedId,user,loadUser}
}
}
</script>
@JacobKorn
Copy link

thanks for this example though, it really helps clarify.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment