Last active
March 27, 2022 22:33
-
-
Save danvega/5b68ed1fa383cd4a0507b018868f7574 to your computer and use it in GitHub Desktop.
Reactive Object Vue
This file contains 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
<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> | |
| |
<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> |
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
I just tested, you can use
Object.assign(user, data)
instead of the for of loop to make it a but more succinct.