Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 7366

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 28, 20242024-11-28T03:09:08+00:00 2024-11-28T03:09:08+00:00

New in Vue.js 3.3: Two-Way Binding With defineModel Macro

  • 60k

With the upcoming VueJS version 3.3 the community once again doesn’t disappoint and releases many useful features for developers to be more productive, and ship features faster.

One of the newly welcomed features is defineModel which allows us to implement much smoother 2-way binding. Let’s demonstrate its usage in the following blogpost.

What is 2-Way Binding?

Two-way binding is a feature in VueJS that allows changes in the data to update the view automatically and vice versa. This means that when the user updates the view, the underlying data is also updated, and when the data is updated programmatically, the view is automatically updated to reflect the new data. It is achieved using the v-model directive, which binds a form input element to a piece of data.

<template>     <input v-model="message" /> </template>  <script setup>     import { ref } from 'vue'      const message = ref('Hello from Bitovi!')  </script> 
Enter fullscreen mode Exit fullscreen mode

Two-way binding is useful because it eliminates the need for manual event handling to keep the view and data in sync, which can be tedious and error-prone. Using v-model is the equivalent of

<template>     <input        :value="message"        @input="message = $event.target.value"      /> </template>  <script setup>     import { ref } from 'vue'      const message = ref('Hello from Bitovi!')  </script> 
Enter fullscreen mode Exit fullscreen mode

Custom 2-way binding

An example may be having a custom search component, allowing the user to type some value into the search, which will display multiple options until he chooses one. This behavior is demonstrated in the following code:

// MySearch.vue  <template>   <div>     <!-- search text input -->     <input v-model="searchRef" type="text" placeholder="Search"/>      <!-- display selected value -->     <div v-if="props.modelValue">       Selected: {{ props.modelValue.title }}     </div>      <!-- results -->     <div v-if="searchRef.length > 3">       <button         v-for="data in store.getLoadedElements"         :key="data.id"         @click="onClick(data)"       >         {{ data.title }}       </button>     </div>   </div> </template>  <script setup lang="ts"> // imports  const store = useStore();  const props = defineProps({   modelValue: {     type: Object as PropType<Element | null>,     required: true,     default: null   } });  const emit = defineEmits<{   (e: "update:modelValue", value: Element): void; }>();  // reference to search input const searchRef = ref<string>("");  // fetch data from API watchEffect(() => {    store.fetchElements(searchRef.value); });  const onClick = (data: Element) => {   emit("update:modelValue", data); }; </script> 
Enter fullscreen mode Exit fullscreen mode

In the above example, to make the custom 2-way binding work, you use defineProps to create a modelValue input property for the component and you use the defineEmits with update:modelValue to notify the parent about the change.

The usage of the above child component is achieved by the following syntax in another component.

<MySearch v-model="someRef" /> <!-- same as --> <MySearch     :modelValue="someRef"     @update:modelValue="someRef = $event" /> 
Enter fullscreen mode Exit fullscreen mode

NOTE: One useful tip is that you can define multiple properties for the MySearch component into the defineProps and defineEmits. The name modelValue is the name for the default value, however creating multiple properties, you can access them in the parent component by <MySearch v-model:first="first" v-model:second="second"/>.

Using defineModel

With the upcoming VueJS version, 3.3 comes a new defineModel macro, you no longer need to write out all the above-mentioned steps to implement custom 2-way binding.

This new feature is available from version-3.3.0-alpha.9, however, It is still considered an experimental feature. If you wish to use it or have difficulty upgrading to version 3.3m, you can still use its alternative, defineModels, from Vue Macros library, by which this feature was inspired. Overal they work the same way.

After completing the installation guidelines, you can use defineModels with the following syntax:

// MySearch.vue  <template>   <div>     <!-- search text input -->     <input v-model="searchRef" type="text" placeholder="Search"/>      <!-- display selected value -->     <div v-if="modelValue">Selected: {{ modelValue.title }}</div>      <!-- results -->     <div v-if="searchRef.length > 3">       <button         v-for="data in store.getLoadedElements"         :key="data.title"         @click="modelValue = data"       >         {{ data.title }}       </button>     </div>   </div> </template>  <script setup lang="ts"> // imports  const store = useStore(); const { modelValue } = defineModels<{ modelValue: Element }>();  // reference to search input const searchRef = ref<string>("");  // fetch data from API watchEffect(() => {   store.fetchElements(searchRef.value); }); </script> 
Enter fullscreen mode Exit fullscreen mode

The macro defineModels replaces the previously used defineProps and defineEmits into one functionality.

Every time, the user passes some value to this component by <MySearch :modelValue="someRef" /> the MySearch component will be updated and also on the other hand, in line 16, when the user selects an element, by modelValue = data, the listener on the parent component will be triggered.

Summary

It’s great to see that the VueJS team recognizes valuable contributions from developers to the VueJS ecosystem and over time, they ship their implementation. With the upcoming version 3.3, VueJS brings us many more useful tools that will speed up our development.

tutorialvuewebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 1k
  • Popular
  • Answers
  • Author

    How to ensure that all the routes on my Symfony ...

    • 0 Answers
  • Author

    Insights into Forms in Flask

    • 0 Answers
  • Author

    Kick Start Your Next Project With Holo Theme

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.