Vue Ref

up:: Vue Composition API

Important

Sounds similar to Vue Refs but works differently!

Ref for reactive values

// Composition API
export default {
setup() {
	const uName = ref('Maximilian'); // Reactive value
	return { userName: uName }
}
 
// Options API
// data() {
//	return {
//		userName: 'Maximilian',
//	}
// }
}

Reassigning values

setup() {
	const uName = ref('Maximilian');
 
	set Timeout(() => {
		uName.value = 'Max';
	}, 2000)
 
	return { userName: uName }
}

Ref for objects

If you use ref for objects the same way you use it for variables, this isn’t going to work. Say you pass on object like so:

return { name: userName.value.name, age: userName.value.age } 

Vue ‘understands’ (through JS Proxies) that something changed in the object. But because you only use the ‘drilled down’ values of the object, the change of the individual properties (which are just Strings and Numbers) isn’t connected to the parent object which Vue keeps track of.

You could ‘fix’ this by passing in the full object:

return { userName: userName } 

Then, in the template you access the stored properties.

Info

Even better, for Objects use Vue reactive.

toRefs

Fun fact: You can also turn all properties of an object into ref-ed variables.

const userRefs = toRefs(user);
return { userName: userRefs.name, age: userRefs.age };