Vue3 and Quasar Tips — ModelValue vs V-Model || Performing Evaluation Before Model Value Change

Selena J
Fortitude Technologies
2 min readMar 30, 2023
Photo by Magnet.me on Unsplash

When starting to learn vue, I always saw v-model being used within components. I hardly had an idea of what it really did, and definitely didn’t know the details of what situations it’s best suited for.

On my project we came across an instance where we wanted a user to confirm they wanted to select another option, as doing this would clear all their other progress. Unfortunately, using v-model meant the variable was automatically being updated, and we didn’t have the chance to trigger a modal before the update occurred.

What we didn’t know at the time was that v-model implements two way binding and can effectively perform two actions under the hood. In order to separate out the v-model operations, we needed to use a combination of modelValue and @update. This way, we can pass in the proposed new value and only assign it to our model under certain conditions.

<q-select
:modelValue="selectedStore"
:options="stores"
label="Select a store"
@update:modelValue="newStore => {catchUpdate(newStore) }"
/>


<script>
import { ref } from "vue";

const selectedStore = ref("");
const stores = ["walgreens", "wegmans", "amazon", "dollar tree"];

function catchUpdate(newValue) {
const update = //decide if you want to discard the old value and replace it with the new one
if(update) {
selectedStore = newValue
}
//the selected option will not change if the code doesn't enter the if statement
}
</script>

Or if you want to use Quasar’s popup dialog to confirm the actions taken:

function catchUpdate(newValue) {
if (shoppingCart.length > 0) {
Dialog.create({
title: 'Warning',
message: 'Selecting new store will delete shopping cart items',
cancel: true,
ok: {
label: 'Start Over',
color: 'red',
},
persistent: true,
}).onOk(() => {
selectedStore = newValue;
clearCart();
});
} else {
//cart is empty: don't need to warn
selectedStore = newValue;
}
}
  • Note: the above example is pseudo code that has not been verified in an IDE

--

--

Selena J
Fortitude Technologies

Hey there :) I am a recent graduate from UVA and currently a Software Engineer working in full stack development. Join me as I share my tips and experiences!