Git Product home page Git Product logo

vue-modal's Introduction

Vue logo

Downloads Downloads Issue Stars

Jenesius Vue Modal

Jenesius vue modal is a progressive and simple modal system for Vue 3 only .

Using this library, you can simply show both one and several modal windows at the same time, integrate with vue-router

Installation

npm i jenesius-vue-modal

Alt Text


The main condition for library initialization is adding a container inside your App.vue file. Note that this container only needs to be mounted once in the main parent component. Opened modals will be shown inside this container.

App.vue

<template>
    <widget-container-modal />
</template>
<script>
    import {container} from "jenesius-vue-modal";
    
    export default {
        components: {WidgetContainerModal: container},
        name: "App"
    }
</script>

Modal show

Methods openModal and pushModal used to display modal windows.

  • openModal - close all previous modals and then display provided component.
  • pushModal - display provided component
import {openModal} from "jenesius-vue-modal";
import SomeVueComponent from "SomeVueComponent.vue";
    
openModal(SomeVueComponent, props);
  • props will provide in your component, example

Methods return promise, in this case promise is resolved modalObject. More information

const modal = await openModal(SomeVueComponent);
// modal {id, close, onclose, closed, instance, on}

Methods

  • openModal - close all modals and then open provided modal.
  • pushModal - add one more provided modal.
  • closeModal- close all modals.
  • popModal - close last opened modal.
  • promptModal - opening a modal window and waiting for a value to be returned. More information

For detailed information about existing methods, follow the link

import {openModal, pushModal, closeModal, popModal} from "jenesius-vue-modal"

How to return value?

Sometimes a modal needs to return a value. This case is described in detail in the following article.

Handle events

Using modalObject you can handle any events:

// Modal.vue
<template>
    <button @click = "emit('update', value)"></button>
</template>

When we click on the button we can handle event using modal.on(eventName, callback)

const modal = await openModal(Modal, {value: 123});
modal.on('update', v => {
    console.log(v); // 123
})

Lifecycle Hooks

All hooks use only returned value(Boolean) for navigation hooks. If function return false or throwing an Error modal window will not be closed.

There are three ways to track the closing of a modal:

  • onclose
const modal = await openModal(Modal, {title: "welcome"});
modal.onclose = () => {
    console.log("Close");
    return false; //Modal will not be closed
}

or if using function declaration you have access to modal Instance by this. This declaration provide way to view data within the modal in the parent's onclose() method:

//Modal.vue
{
    props: {title: String},
    data : () => ({info: "Version x.x.x"}),
    methods: {
        update(){}
    }
}
//...
modal.onclose = function(){
    // Has access to the context of the component instance this.
    this.title; // "welcome"
    this.info;  // "Version x.x.x"
    this.update();
}
  • default component
export default {
    props: {},
    data: () => ({isValidate: false}),
    beforeModalClose(){
        if (!isValidate) return false; //modal will not be closed while isValidate === false
    }
}
  • Composition style
import {onBeforeModalClose} from "jenesius-vue-modal"
export default{
    setup() {
        onBeforeModalClose(() => {
            console.log("Close");
        });
    }
}

Async/Await

Hooks also can be asynchronous functions:

async beforeModalClose(){
    await doSome();
    return false; // This modal can not be closed!
}

or

beforeModalClose(){
    return Promise(resolve => {
        setTimeout(() => resolve(true), 2000); //Modal will closed after 2 second
    })
}

Integration with VueRouter

For integrate modals into VueRouter you need to initialize your application:

  • Provide router to the useModalRouter:
import {createWebHistory, createRouter} from "vue-router";
import {useModalRouter} from "jenesius-vue-modal";

const router = createRouter({
    history: createWebHistory(), 
    routes: [...],
});

useModalRouter.init(router); //Saving router
  • Wrap your component in a route handler:
import Modal from "Modal.vue"

const routes = [
    {
        path: "/any-route",
        component: useModalRouter(Modal) // Wrap of your VueComponent
    }
]

Now, when route will be /any-route the Modal window will open. For more information see Docs.

Style and Animation

Please refer to the documentation to change the styles or animations of modals.

Example VueModalComponent

WidgeTestModal.vue

<template>
    <p>{{title}}</p>
</template>
<script>
    export default {
        props: {
            title: String
        }
    }
</script>

To show this component

import {openModal} from "jenesius-vue-modal"
import WidgeTestModal from "WidgeTestModal.vue";

openModal(WidgeTestModal, {
    title: "Hello World!"
});

Do you like this module? Put a star on GitHub

vue-modal's People

Contributors

anshirko avatar bog-danius avatar husudosu avatar jenesius avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

vue-modal's Issues

Build error with latest version

It seems that an error occurs in 1.1.0 and later versions.

ERROR  Failed to compile with 1 error                                                                                                                     18:37:10
error  in ./node_modules/jenesius-vue-modal/plugin/index.js

Module parse failed: Unexpected token (44:6)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| class ModalObject{
|
>     id;
|     component;
|     params;

 @ ./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader-v16/dist??ref--0-1!./src/App.vue?vue&type=script&lang=js 4:0-45 10:26-35
 @ ./src/App.vue?vue&type=script&lang=js
 @ ./src/App.vue
 @ ./src/main.js
 @ multi (webpack)-dev-server/client?http://192.168.0.101:8080&sockPath=/sockjs-node (webpack)/hot/dev-server.js ./src/main.js

test

Describe the bug
A clear and concise description of what the bug is.

Please complete the following information:

  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

Access to modalObject

Add modalController in props.

Access:

props: {
  modalController: Object
}

It's usefull for somethings?

Onback

When user press back - close window.
Maybe add customer router handler
Or, need to write docs about it
....
Add configuration param

Lifecycle injection APIs can only be used during execution of setup()

Hello,

I try to integrate the library in a Vue3/TS project mostly using the Composition API but I face some issues. First there are those warnings in the console and then when trying to use openModal to open a Component in the modal container there is an error. This is probably related to the warnings.

// App.vue
<script lang="ts">
import { defineComponent } from 'vue'
// @ts-expect-error no TS types available yet
import { container } from 'jenesius-vue-modal'
export default defineComponent({
  components: {
    WidgetContainerModal: container,
  },
})
</script>
<template>
  <div id="app">
    <router-view />
    <WidgetContainerModal />
  </div>
</template>
// Component.vue simplified
<script setup lang="ts">
// @ts-expect-error no TS types available yet
import { openModal } from 'jenesius-vue-modal'
import ExampleModal from './ExampleModal.vue'

</script>
<template>
  <div>
    <button text="Open Modal" @click="openModal(ExampleModal)">Open Modal</button>
  </div>
</template>

Here are the console warnings

[Vue warn]: onMounted is called when there is no active component instance to be associated with. Lifecycle injection APIs can only be used during execution of setup(). If you are using async setup(), make sure to register lifecycle hooks before the first await statement.

which seems related to this

// extracted from jenesius-vue-modal.cjs.js
var script = {
  setup(){

    vue.onMounted(initialize);

  return () => {
    return vue.h(vue.TransitionGroup, {name: configuration.animation}, {
      default: () =>modalQueue.value.map(modalObject => {
        return vue.h(script$1, {component: modalObject.component, params: modalObject.params, key: modalObject.id, id: 
          modalObject.id});
	})
      })
    }
  },
  components: {WidgetContainerModalItem: script$1}
};

and probably related to useTransitionState() from the dependencies

I also have this warning

runtime-core.esm-bundler.js:6870 [Vue warn]: Invalid VNode type: Symbol(Fragment) (symbol) 
  at <TransitionGroup name="modal-list" > 
  at <WidgetModalContainer> 
  at <App>

And finally the error when I try to open the modal

jenesius-vue-modal.cjs.js:771 Modal Container not found. Put container from jenesius-vue-modal in App's template. Check documentation for more information
localhost/:1 Uncaught (in promise) Modal Container not found. Put container from jenesius-vue-modal in App's template. Check documentation for more information

I probably make something wrong but do not understand what.

Thanks for the help

promptModal

Main goal: to add the ability to connect to linear modal windows.
A linear modal window is a window whose main task is to return a value. Referencing promt in JavaScript.
Tasks:

  • implementation of the promtModal method (Or another name, while being discussed)
  • value return implementation

Principle of operation:

const result = promptModal(VueModal);
// VueModal.vue
<template>
  <div>
    <button @click = "change(1)">up</button>
    <button @click = "change(-1)">down</button>
  </div>
</template>
<script setup>
  function change(v) {
    emit('close', v);
  }
</script>

This example demonstrates a modal window that will return either 1 or -1 (undefined if it was closed with Esc or background)

add event closed

Hello,

there are many times that it's needed to call API request after modal has been closed and result of modal was true

because sometime you need to just call API when a modal closed and also result of modal was true .

so it's needed to pass variable in when closing modal with closeModal() Function

and this variable is used like this

  modal.onClosed = (result) => {
    if (result) {
      // get data from api
    }else{
      // do nothing
    }
  }

imagine if a user just opened a modal and do nothing
in this situation API call should not fired .

onClose callback

Add global onClose hook
Add onClose for modal

onClose(callback)
onClose(modalId, callback)

Global and Local Config

Add the third param for next methods:

  • openModal
  • pushModal

method(VueComponent, params, config)

The local config affect only for one ModalContainerItem
Create ConfigDto


import {config} from "jenesius-vue-modal"

config(config) is a same function, but set params for global configuration

Force methods

There is sense to add force methods(forceCloseModal, forcePopModal, forceOpenModal)
WITHOUT next function

For example:
If modal will have:

beforeModalClose: (next) => next(false)

forcemethods can close this windows

Type Supporting

When we provide Component we can get the types for props:

import MyComponent from "./mycomponent.vue";
type MyComponentProps = InstanceType<typeof MyComponent>["$props"];

Its will be amazing!

Event of closing

Add event to onclose, beforeModalClose, onBeforeModalClose guards

Configuration

escape: Boolean(true). Close last opened modal window.

ModalException

If methods popModal and closeModal cant close the modal window, they throw exception. Its the right way?

Modal update?

If i dont want to open one more window, i just want to change props.
modal.update(NEW_PROPS)

Uncaught (in promise) TypeError: Class constructor EventEmitter cannot be invoked without 'new'

Hi,
I am using Vue 3 Composition api

and , I've done setup as document

But i have this error when I want to open it

image

jenesius-vue-modal.cjs.js:495 Uncaught (in promise) TypeError: Class constructor EventEmitter cannot be invoked without 'new'

app.vue

<script setup lang="ts">
import { RouterView } from 'vue-router'
import {container} from "jenesius-vue-modal";
</script>

<template>
 <container  />
  <RouterView />
</template>

homeComponent.vue

import { openModal } from "jenesius-vue-modal";
import MyCom from '@/components/Common/MyCom.vue'

function open() {
  openModal(MyCom, { message: "Welcome" })
}

MyCom.vue

<script setup lang="ts">
</script>
<template>
  <div class="header1">
    Hello
  </div>
</template>

How can I fix this ?

Design pack

Выделить

  • Универсальное окно
  • Confirm
  • Alert
  • Info

prevent close when click outside

Hello,

I want to know if there is any way to prevent modal close when click modal outside .

I know I can prevent it like below but it is not good for me because I want to close it with emmited event and this can't do that

  modal.onclose = () => {
    return false;
  }

is there any way ?

Prevent ESC from closing modal in VueRouter

Is your feature request related to a problem? Please describe.
Maybe this exists and I haven't seen it, but it would be nice to be able to pass configuration options when using VueRouter. For instance, I would like to disable closing the modal on ESC key press when using VueRouter.

Describe the solution you'd like
When I open a modal page using the VueRouter integration, I may have other functionality on that page that requires users to use the ESC key. In this case, if the user presses on the ESC key, the entire page closes. I'd like a solution where I can disable the ESC key when using VueRouter.

Describe alternatives you've considered
Maybe something like this to the composable?

useModalRouter.init(router, { escClose: false });

I know that in theory, we can tap into the onBeforeModalClose hook like this:

// App.vue

onBeforeModalClose((event) => {
    // prevent modal from closing if the user pressed the `ESC` key
   return false
});

However, in this case, it will be nice to add a flag in the event to show that the user pressed the ESC key. at the moment, the event contains only one flag called background, which I believe indicates that the user clicked on the background to close the modal. I suggest adding another flag, eg isESC or something similar.

Responsive not supported?

Thank you for the wonderful library 😄
It is helpful because there was no modal library that can be used properly with Vue3.

It doesn't seem to be responsive, but I solved it by adding the following CSS.

.widget__modal-container__item-back {
  position: absolute;
}

.widget__modal-container__item {
  display: flex;
  align-items: center;
  justify-content: center;
}

Modal Store and execute modal by name.

Is your feature request related to a problem? Please describe.
In one of my project, I have a core of site, that use modal for default functionality. In those case it was show confirm modal when
we want execute some request. In this case we can use openModal('confirmation', { text: 'Do You want start removing data?' })

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

const store = {
  'confirmation': ModalConfirmation
  'apply': ModalApply,
  'notification': ModalNotification
}
openModal('confirmation')
pushModal('apply')
promptModal('notification')

Additional context
Add any other context or screenshots about the feature request here.

Typescript support

Hello, this is more a question than an issue but could not use a label :)

Do you plan on adding Typescript support adding the types, to enable the usage of your library in a TS project without shutting down TS on every import?

// @ts-expect-error no TS types available yet
import { openModal } from 'jenesius-vue-modal'

Thanks in anticipate.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.