vue.jsvuetify.js

Initiate a function with v-checkbox when the item is clicked by the user


I have a v-checkbox in my vuetify app that is preloaded with some data from the database on load. However, the user can change the model value of this to true or false manually overwriting the data imported by the database. However, I do not know how to target my function I want it to run if its the user that manually changes it. I do not want it to run when the data is first loaded and fills the model.

I have tried using watch but again it will initiate the function on load which I do not want it to do . The change event will also initiate on load data so that doesnt seem to work. Then there is blur which I tried and that does not work because it requires you to click on the item and change it then click somewhere else on the screen which creates a delay when my function should run exactly when its clicked.

My code is as follows:

<v-checkbox
  v-model="approvalLanguageModel"
  hide-details
  color="primary"
  label="Check this if the email will include the approval letter (WARNING: Changing this option will overwrite any current edits to the draft email below with the updated email template!)."
  @blur="createDraftEmailTemplate()"
/>

Maybe I should just be using click event with my method and call it a day? Does click event always result in model change/ update to component?


Solution

  • Use @update:model-value as it's an update event that comes from v-checkbox triggered by a user interaction. If you set the initial value of v-checkbox with some script code, e.g. approvalLanguageModel.value = true, that won't cause @update:model-value to run.

    <v-checkbox
      v-model="approvalLanguageModel"
      hide-details
      color="primary"
      label="Check this..."
      @update:model-value="myFunction"
    />
    

    See this Vuetify Playground demo that mocks an API call (using setTimeout) to set the initial value. Notice no console log appears when the initial value is set. Interacting with the checkbox and clicking it is the only way for the function to run.