"Exploring the Synchronization Feature in Vue.js 2.3 with Element UI Dialog Components

Recently, I've encountered some changes while using Element UI with the latest release of Vue.js 2.3

In my project, a dialog should only be displayed if certain conditions are met:

private.userCanManageUsers && private.pendingUsers.length > 0 && private.pendingDialogVisible

I attempted to implement the new attribute visible.sync, you can find more information in the documentation here

While it works fine with a single condition, it fails to work when there are multiple conditions present.

Working Case

<el-dialog
       :visible.sync="private.pendingDialogVisible"                 
</el-dialog>

Not Working Case

<el-dialog
       :visible.sync="private.userCanManageUsers && private.pendingUsers.length > 0 && private.pendingDialogVisible"           
    </el-dialog>
  1. Is there a solution to use el-dialog with visible.sync and multiple conditions?
  2. If not, what steps should I take to make it function as expected?

Answer №1

The issue arises from a misinterpretation of the functionality of the sync in Vue.

In Vue 2.3, the sync feature acts solely as an event registration to enable two-way binding. According to the documentation:

In version 2.3, we reintroduced the .sync modifier for props, which is essentially syntax sugar that automatically expands into an additional v-on listener: The following

<comp :foo.sync="bar"></comp>

is expanded to:

<comp :foo="bar" @update:foo="val => bar = val"></comp>

To put it simply, this means that since it facilitates two-way binding, you cannot use multiple properties (as a boolean expression) or return a method's value because you need to both read from and write to the same value.

To clarify, no, you can't achieve what you're trying to do using sync in its current usage. I personally find the library's implementation unclear and leading to complex workarounds.

However, you can bind visibility to a single property with :visible.sync and trigger it based on your state in this example:

Template:

<div id="app">
  <el-dialog title="Shipping address" :visible.sync="showDialog" 
    :before-close="beforeCloseHandler"
    @close="cond1 = true; cond2 = false;">
  </el-dialog>
  <button @click="cond1 = true; cond2 = false; showDialog = true;">Open Dialog</button>
</div>

Javascript:

var Main = {
    data() {
      return {
        showDialog: true,
        cond1: true,
        cond2: true,
      };
    },
    methods: {
      beforeCloseHandler: function (done) {
        if (this.cond1 && this.cond2) {
            console.log('hit close');
            done();
        } else {
            console.log('rejected close');
        }
      }
    }
  };
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')

We can associate the display with a single property, manage dismissal with the :before-close handler, and adjust show conditions via a button click event. It may not be perfect, but it offers a potential workaround.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error Encountered in Next.js: PDFtron Webviewer - Troubleshooting

I'm currently working on a website that incorporates a dynamically imported PDF viewer within the page. When running the code locally, everything operates smoothly with no errors. However, when executing the "npm run build" command, I encounter the fo ...

Convert time display to a 24-hour format using JavaScript

I managed to convert the time format from GMT to my browser's local time using the following JavaScript code: var newDate = new Date(timeFromat); timeFormat = newDate.toLocaleString(); Now, I want to change the time format to a 24-hour clock format ...

Extracting data from websites: How to gather information from dynamic HTML elements

On the website I am exploring, there is a dynamic graph with descriptions below it that keep changing. My goal is to extract all these trajectory descriptions. The HTML code snippet related to the description area looks like this: <div class="trajDesc ...

"Adding an Image to Another Image in HTML or JavaScript: A Step-by-Step

Hello there! I'm currently working on creating a status bar where I can add an image after another image. Let me explain my idea clearly. So, I have two images in GIF format: one is white and 10x10px, and the other one is black and also 10x10px. On ...

Why does React / NextJS throw a "Cannot read properties of null" error?

In my NextJS application, I am using useState and useEffect to conditionally render a set of data tables: const [board,setBoard] = useState("AllTime"); const [AllTimeLeaderboardVisible, setAllTimeLeaderboardVisible] = useState(false); const [TrendingCreat ...

What causes the syntax error when attempting to delete using ng-init in a straightforward manner?

Take a look at this short code snippet (jsfiddle): <div ng-app="App" ng-init="foo={a: 20}; delete foo['a']"> </div> This causes a syntax error in both Firefox and Chrome browsers. But why? The syntax error states, "Token 'fo ...

Interested in learning how to filter nested tables?

After successfully integrating a filter code snippet, I encountered an issue with the filter not recognizing data tables that can only be inserted as nested tables. Due to my limited knowledge of JavaScript/CSS, I'm unsure if this problem can be resol ...

Managing file system operations in Node.js

What is the most effective way to manage file access in node.js? I am currently developing an http-based uploader for exceptionally large files (10sGB) that allows for seamless resumption of uploads. I am trying to determine the optimal strategy for handl ...

Differentiating a path element in SVG by dynamically adding color using d3 and react

I have a unique SVG icon: <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <circle cx="12" cy="12" r="12" /> <path class="svg-fill" d="M12,2A10,10,0,1,0,22, ...

What is the best way to transform a date such as '2021-06-01T11:17:00-07:00' into the corresponding date and time for a specific location (New Delhi) using JavaScript?

How can I convert a date in the format '2021-06-01T11:17:00-07:00' to ISO standard? What does this format represent? let date = new Date('2021-06-01T11:17:00-07:00'); console.log(date.getHours() + " :" + date.getMinutes()); I ...

Transform a numerical variable into a string data type

I am faced with a situation where I have a variable named val which is currently set to the number 5. Now, my goal is to update the value of val so that it becomes a string containing the character "5". Could someone guide me on how to achieve this? ...

Saving an HTMLCanvasElement as a JPEG in Laravel

I have successfully integrated a cropping script into my Vue Component that can return either an image or an HTMLCanvasElement. After using the script to crop an image, my component's crop method then sends an axios post call to my upload function. Be ...

confirmation message upon completing a form submission

<script> var remainingCredit = document.getElementById("cor_credit"); var remaining = document.getElementById("remain_credit"); function validateForm() { if (remaining.value < remainingCredit.value) { return conf ...

Create a server directory structure that populates multiple HTML dropdown lists using either jQuery or AJAX

As a novice navigating jQuery and Ajax, I find myself faced with a specific challenge. My current situation involves a structured set of directories on a server. My goal is to populate a dropdown dynamically with this file hierarchy. Upon click ...

What are the best practices for utilizing databases with both Javascript and JSF frameworks?

I am currently following the recommendations provided by @BalusC, with additional guidance available here. (The reason I'm posting this here is because it's not related to my previous question). My goal is to retrieve data from my database and d ...

The React/Redux application is experiencing difficulties with API calls, as they are returning empty responses and the actions are not being triggered

Hey there, I'm currently working on a React Native app and running into some issues with making API get requests. It seems like the response is throwing an error and the action isn't executing properly. I'll share my code below, so if anyone ...

Receiving JSON objects from Javascript in Django Views

When I attempt to pass a Json Object value from making an API call to my views.py in Django template, I encounter difficulty retrieving the value after an ajax call. let application = JSON.parse(sessionStorage.getItem("appId")); let kycStatus = a ...

How much worth does an unfilled text input box hold?

I've been working on integrating a search feature and I'm having an issue with the functionality. Below is the code snippets for both HTML and JS: HTML <form> <input type="text" ng-model="searchVar" class="searchbox"> <in ...

Drag and drop non-event elements onto events using jQuery FullCalendar

I'm facing a challenge with dragging and dropping an employee name onto an event using jQuery UI draggable/droppable. I want to drag an employee (as shown in the picture) onto an event, but the 'employee' is not an event itself. <script& ...

Steps for connecting data to a react table

This is my first time working with React and I want to display the following data (id, name, status, and quantity): interface Goods { id: number; name: string; status: string; quantity?: number; } export const getGoods = (): Promise<Goods[]> ...