Display the component's template when invoking methods

While immersing myself in learning Vue.js, I find myself in need of some guidance. Can someone kindly review my code and point me in the right direction? Below is the code snippet along with an explanation of what I am trying to achieve.

Below is the Vue.js app I am working on:

Vue.component('o365_apps_notifications', {
    template:
    `
    <div class="notification is-success is-light">
        // Call the name here and if added/removed.
    </div>
   `,

});

new Vue({
    name: 'o365-edit-modal',
    el: '#o365-modal-edit',
    components: 'o365_apps_notifications',
    data() {
        return {
            list: {},
            movable: true,
            editable: true,
            isDragging: false,
            delayedDragging: false,
            options: {
                group: 'o365apps',
                disabled: true,
                handle: '.o365_app_handle',
            }
        }
    },
    methods: {
        add(index, obj) {
            console.log(obj.name);
            this.$data.list.selected.push(...this.$data.list.available.splice(index, 1));
            this.changed();
        },
        remove(index, obj) {
            console.log(obj.name);
            this.$data.list.available.push(...this.$data.list.selected.splice(index, 1));
            this.changed();
        },
        checkMove(evt) {
            console.log(evt.draggedContext.element.name);
        },
    },
});

Here is the modal structure:

<div id="o365-modal-edit" class="modal">
    <div class="modal-background"></div>
    <div class="modal-card px-4">
        <header class="modal-card-head">
            <p class="modal-card-title">Applications</p>
            <button class="delete" aria-label="close"></button>
        </header>
        <section class="modal-card-body">
            <div class="container">
                <div id="o365-modal-edit-wrapper">
                    <div class="columns">
                        <div class="column is-half-desktop is-full-mobile buttons">
                            // Empty
                        </div>
                        <div class="column is-half-desktop is-full-mobile buttons">
                            // Empty
                        </div>
                    </div>
                </div>
            </div>
        </section>
        <footer class="modal-card-foot">
            <o365-apps-notifications></o365-apps-notifications>
        </footer>
    </div>
</div>

My Objective:

Within my modal, I have included the o365_apps_notifications HTML tag, where the add() and remove() methods log a name each time they are triggered using console.log(obj.name);. Additionally, the checkMove method displays the same name during the dragging process as illustrated below:

  1. How can I ensure that my component renders and outputs the name within the modal footer? I have attempted various methods but haven't been successful in triggering the component.

  2. Is there a specific approach to implement a fading effect on the component after a certain period?

Your assistance is highly appreciated!

Answer №1

There are a couple of issues that need to be addressed:

  1. The notification component has been declared with underscores (o365_apps_notifications), but the modal's template uses hyphens. It is important to maintain consistency in naming conventions (hyphens are preferred).

  2. The notification component is declared globally using Vue.component, but it appears that you are trying to add it as a local component within the modal using components. Only one registration is necessary (the global registration should suffice).

<o365-apps-notifications>

The notification component should have public props for the item name and state:

Vue.component('o365-apps-notifications', {
  props: {
    item: String,
    isAdded: Boolean
  },
})

Subsequently, the template can use data binding to display these props.

Vue.component('o365-apps-notifications', {
  template:
   `<div>
      {{ item }} {{ isAdded ? 'added' : 'removed '}}
    </div>`
})

For the fade transition effect, conditional rendering based on a local Boolean data property like show should be implemented:

Vue.component('o365-apps-notifications', {
  template:
   `<div v-if="show">
      ...
    </div>`,
  data() {
    return {
      show: false
    }
  }
})

...and include the <transition> element along with CSS styles for the fade effect:

Vue.component('o365-apps-notifications', {
  template:
   `<transition name="fade">
      <div v-if="show">
        ...
      </div>
    </transition>`,
})
.fade-enter-active, .fade-leave-active {
  transition: opacity .5s;
}
.fade-enter, .fade-leave-to {
  opacity: 0;
}

To enable automatic fading out of data, a watch on the item is necessary. This watch function sets show=true and then resets it to false after a delay:

Vue.component('o365-apps-notifications', {
  watch: {
    item(item) {
      if (!item) {
        return;
      }
      this.show = true;

      clearTimeout(this._timer);
      this._timer = setTimeout(() => this.show = false, 1000);
    }
  }
})

Usage

In the modal component, define local data properties to hold the currently added/removed item:

new Vue({
  el: '#o365-modal-edit',
  data() {
    return {
      changedItem: null,
      changedItemIsAdded: false,
    }
  },
})

Also update the add() and remove() methods to assign values to these properties:

new Vue({
  methods: {
    add(index, obj) {
      this.changedItem = obj.name;
      this.changedItemIsAdded = true;
    },
    remove(index, obj) {
      this.changedItem = obj.name;
      this.changedItemIsAdded = false;
    },
  },
})

Finally, bind these properties to the notification component's props within the modal component's template:

<o365-apps-notifications :item="changedItem" :is-added="changedItemIsAdded"></o365-apps-notifications>

See the demo for reference.

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

Gather various data from multiple tables with Laravel

I am seeking help to find a solution to my current issue. I am working with various tables and wondering how I can create a custom collection that gathers specific data from multiple tables based on logical relationships. My goal is to return this collec ...

What steps should I take to customize the design of my Stripe subscription payment page?

I am having trouble with the alignment of the subscription payment page, which is currently displaying all information in a single line. I would like to format it like a traditional payment form with card number, CVV, and expiry on separate lines rather th ...

Ways to retrieve a service variable within a delegated function (callback)

I am currently using a service that has a variable which needs to be updated by the service itself. However, I am facing an issue where I cannot access the variable in anonymous or delegated functions. (function() { 'use strict'; angular ...

Why is it that the edit or delete button is not functioning when I attempt to click on the next page?

Having an issue with my script. It works fine for editing and deleting on the first page, but when I navigate to the next page, those functionalities stop working. Can anyone help me troubleshoot this problem? <script> $(function(){ $(&ap ...

The error message "Uncaught (in promise) ReferenceError: dispatch is not defined" indicates that

Currently, I am utilizing vuex with index.js and auth.js stored in the store folder. My goal is to perform a basic sign-in operation within my signin.vue by calling an action from the store. However, I encountered the error 'Uncaught (in promise) Refe ...

Issues with response functionality in Node.js (Openshift) using express

I am currently working with OpenShift and Node.js to calculate the average rating for each result. However, I am facing an issue where the response is not being displayed even though the console logs show the correct data. The console displays 3.9454323, ...

Obtain the value of a JavaScript form with a dynamically generated field name

I am struggling with a simple javascript code and for some reason, it's not working. var number = 5; var netiteration = "net"+number; // now netiteration is equal to net5 var formvalue = document.forms.myformname.netiteration.value; Why is this co ...

Is there a way to use JSON.stringify() to post multiple arrays at once?

Trying to send multiple arrays to the controller using Ajax post. Initially, there is a model structured like this: public class EnrollmentOptionsVM { public virtual string OptionID{ set;get;} public virtual string UserChoice { set;get;} p ...

Tips for keeping the Menu bar at the top of the page while scrolling from the middle

I came across a technique mentioned here that I wanted to implement. I used this jsfiddle link (which worked well) to create my own version http://jsfiddle.net/a2q7zk0m/1/, along with a custom menu. However, now it seems like it's not working due to a ...

A guide on choosing a custom button color and automatically reverting to its original color when another button is clicked

I have a collection of 24 buttons, all in a dark grey (#333333) shade. Whenever I click on one of the buttons, it changes to a vibrant blue color (#0099ff), which is functioning correctly. However, when I proceed to click on another button, the previous ...

Encountering an error message stating "Type does not match FunctionComponent<Props>" and "Type is lacking the properties from type 'React Element<any, any>'"

As I work on integrating TypeScript into my code, I keep encountering an error that seems to be related to my Props type. The specific error message I'm facing is: Type '({ volume, onload, isMuted, src, mediaType, ...config }: PropsWithChildren&l ...

What is the process for inputting a value within single quotation marks?

I'm working with a code snippet that looks like this: for(var j=0; j < this.arr.length; j++) { arr.push({ id: 'j', label: this.arr[j], display: () => this.arr[j] }) } I am curious about ho ...

Unexpected behavior encountered when using the $http.post method

I've been working with a component that I utilized to submit data to the Rest API. The code snippet for the component is as follows: (function(angular) { 'use strict'; angular.module('ComponentRelease', ['ServiceR ...

issue encountered when filling out a dropdown menu using a JSON data structure

Seeking assistance with populating a button dropdown in angularjs. Encountering the error message: "Unexpected end of expression: data.WotcSummary "|. Any ideas on what might be causing this issue? Here is the JavaScript file code snippet: WotcDashBoard ...

Is it important to avoid two-way databinding in Angular 2 when it is not needed?

I have been conducting extensive research to determine if there would be any negative performance impact if I consistently use two-way data binding (ng-model) in all of my forms instead of one-way data binding. I am aware that with Angular 1, a new watch ...

Is it possible to access variables within functions from outside of them?

async function checkPlayersOnline() { const response = await fetch("http://ip:port/dynamic.json"); const playersData = await response.json(); console.log(playersData.clients); } Is it possible to access the playersData inside another func ...

When attempting to execute a function within another function in JavaScript, a ReferenceError is triggered

I recently developed a straightforward app that utilizes the Google Drawing Library (https://developers.google.com/maps/documentation/javascript/examples/drawing-tools) to allow users to draw circles on a map. The first circle represents the source locatio ...

The "Find Usages" feature in Intellij does not have functionality across Lerna packages

I've set up a monorepo with typescript using Lerna, but I'm encountering a bug or misconfiguration related to the "find usages" feature. You can find a demo of the issue in my GitHub repo here: https://github.com/mcclaskc/IntellijLernaExample ...

Unable to render content after using array.push(....)

<template> <div class="overlay_CompareItem"></div> <div class="modal_CompareItem"> <header class="modal__header_CompareItem"> <h2>Compare Computers</h2> <button ...

What is the best way to navigate through an HTML node tree, including all of its sub elements, when walking through

Do you know of a way to iterate through the entire hierarchy of HTML elements and check each one for attributes and more without using JavaScript? We currently have a JavaScript solution that iterates through each child element and all their descendants. ...