Vue.js modal

Version 2.0.0+ potentially has breaking changes. Please take a look at the changelog below:

  • Using ResizeObserver instead of MutationObserver
  • Using transition states to coordinate modal & overlay transitions (instead of delays)
  • Using prettier
  • Overlay is not a parent of the modal anymore (now has independent transition)
  • Renamed Event.stop => Event.cancel
  • Removed v--modal-background-click element
  • Removed v--modal default class
  • Removed "delay" property - component is relying on modal & overlay transition durations
  • Added naive implementation of focus trap
  • Added source-maps
  • Added hideAll for dynamic modals
  • Fix: dialogs not working when componentName is changed
  • Fix: ActiveElement is blurred after before-open event is fired (it is possible to cache document.activeElement now)

 

Simple to use, highly customizable, mobile-friendly Vue.js 2.0+ modal with SSR support. http://vue-js-modal.yev.io/

Changelog

 

Demo: http://vue-js-modal.yev.io/

Install

npm install vue-js-modal --save

How to use

Include plugin in your main.js file.

 

import VModal from 'vue-js-modal'

 

Vue.use(VModal)

 

/*

By default, the plugin will use "modal" name for the component.

If you need to change it, you can do so by providing "componentName" param.

 

Example:

 

Vue.use(VModal, { componentName: "foo-modal" })

...

<foo-modal name="bar"></foo-modal>

*/

Create modal:

 

<modal name="hello-world">

  hello, world!

</modal>

Call it from anywhere in the app:

 

methods: {

  show () {

    this.$modal.show('hello-world');

  },

  hide () {

    this.$modal.hide('hello-world');

  }

}


You can easily send data into the modal:

 

this.$modal.show('hello-world', { foo: 'bar' })

And receive it in beforeOpen event handler:

 

<modal name="hello-world" @before-open="beforeOpen" />

 

methods: {

  beforeOpen (event) {

    console.log(event.params.foo);

  }

}

If you use Bower package manager - you will have to initialize library differently:

 

Vue.use(window["vue-js-modal"].default);

Dialog

It is a simplified version of the modal, which has most parameters set by default and is pretty useful for quick prototyping, showing alerts or creating mobile-like modals.

To start using <v-dialog /> you must set dialog: true in plugin configuration:

 

Vue.use(VModal, { dialog: true })

And include it in your project:

 

<v-dialog />

Call it (all params except of “text” are optional):

 

this.$modal.show('dialog', {

  title: 'Alert!',

  text: 'You are too awesome',

  buttons: [

    {

      title: 'Deal with it',

      handler: () => { alert('Woot!') }

    },

    {

      title: '',       // Button title

      default: true,    // Will be triggered by default if 'Enter' pressed.

      handler: () => {} // Button click handler

    },

    {

      title: 'Close'

    }

 ]

})

 

Dynamic Modals

In order to instantiate modals at runtime (for lazy-loading or decluttering templates), it is possible to create modals dynamically.

To start using this feature you must set dynamic: true in plugin configuration:

 

Vue.use(VModal, { dynamic: true, dynamicDefaults: { clickToClose: false } })

And include the <modals-container /> component it in your project:

 

<modals-container />

Alternatively, the modals container can be automatically appended to the document body once the plugin is loaded using injectModalsContainer: true:

 

Vue.use(VModal, { dynamic: true, injectModalsContainer: true })

Call it (the first argument is the component definition, the second are component properties, the third modal parameters, and the fourth the modal event listeners):

 

this.$modal.show({

  template: `

    <div>

      <h1>This is created inline</h1>

      <p>{{ text }}</p>

    </div>

  `,

  props: ['text']

}, {

  text: 'This text is passed as a property'

}, {

  height: 'auto'

}, {

  'before-close': (event) => { console.log('this will be called before the modal closes'); }

})

It can also be used with .vue files:

 

import MyComponent from './MyComponent.vue'

 

this.$modal.show(MyComponent, {

  text: 'This text is passed as a property'

}, {

  draggable: true

})

Other than defining the name modal parameter, it's also possible to close dynamic modals emitting a 'close' event:

 

this.$modal.show({

  template: `

    <div>

      <p>Close using this button:</p>

      <button @click="$emit('close')">Close</button>

    </div>

  `

})

If using the injectModalsContainer flag, the first mounted Vue instance without parents will be treated as the application root. This is only important to keep in mind if more than one root Vue instance is being used, which is unlikely. But if that's the case, the root to use can be indicated with the root parameter when invoking dynamic modals or modifying this plugin's rootInstance attribute:

 

import App from './App.vue'

import VModal from 'vue-js-modal'

 

const app1 = new Vue({

  el: '#app-1',

  render: h => h(App)

})

 

const app2 = new Vue({

  el: '#app-2',

  render: h => h(App)

})

 

VModal.rootInstance = app2

It is possible to set default property values for dynamic modals.

Example:

 

 

import VueJsModal from 'plugin'

 

Vue.use(VueJsModal, {

  dynamic: true,

  dynamicDefaults: {

    foo: 'foo'

  }

})

 

{

    showDynamicRuntimeModal () {

      this.$modal.show({

        template: `

          <div class="example-modal-content">

            <p>{{ text }}</p>

            <p>Default Property: {{ foo }} - value is "foo"</p>

          </div>

        `,

        props: ['text', 'foo']

      }, {

        text: 'This text is passed as a property'

      })

    },

}

For more examples please take a look at vue-js-modal.yev.io.

Note: keep in mind that there are some limitations in using dynamic modals. If you need full functionality then use ordinary modal instead.

SSR

Include plugin in your nuxt.config.js file:

 

module.exports = {

  plugins: ['~plugins/vue-js-modal']

}

And your plugins/vue-js-modal.js will look like:

 

import Vue from 'vue'

import VModal from 'vue-js-modal/dist/ssr.index'

 

Vue.use(VModal)

Extracted CSS

There is also an SSR build with CSS file extracted. Take a look in /dist folder.

Properties

NameRequiredTypeDefaultDescription
nametrue[String, Number] Name of the modal
delayfalseNumber0Delay between showing overlay and actual modal box
resizablefalseBooleanfalseIf true allows resizing the modal window, keeping it in the center of the screen.
adaptivefalseBooleanfalseIf true, modal box will try to adapt to the window size
draggablefalse[Boolean, String]falseIf true, modal box will be draggable. If string, a selector to use as a handle for dragging
scrollablefalseBooleanfalseIf height property is auto and the modal height exceeds window height - you will be able to scroll modal
resetfalseBooleanfalseResets position and size before showing modal
focus-trapfalseBooleanfalseEnable focus trap (plugin uses naive implementation of the focus trap)
clickToClosefalseBooleantrueIf set to false, it will not be possible to close modal by clicking on the background
transitionfalseString Transition name
overlayTransitionfalseString'overlay-fade'Transition name for the background overlay
classesfalse[String, Array]''Classes that will be applied to the modal box
stylesfalse[String, Array, Object] Style that will be applied to the modal box (currently only supports strings)
widthfalse[String, Number]600Width in pixels or percents (e.g. 50 or "50px", "50%")
heightfalse[String, Number]300Height in pixels or percents (e.g. 50 or "50px", "50%") or "auto"
minWidthfalseNumber (px)0The minimum width to which modal can be resized
minHeightfalseNumber (px)0The minimum height to which modal can be resized
maxWidthfalseNumber (px)InfinityThe maximum width of the modal (if the value is greater than window width, window width will be used instead
maxHeightfalseNumber (px)InfinityThe maximum height of the modal (if the value is greater than window height, window height will be used instead
pivotXfalseNumber (0 - 1.0)0.5Horizontal position in %, default is 0.5 (meaning that modal box will be in the middle (50% from left) of the window
pivotYfalseNumber (0 - 1.0)0.5Vertical position in %, default is 0.5 (meaning that modal box will be in the middle (50% from top) of the window
rootfalseVue instancenullRoot instance to obtain modal container from. This property is only necessary when using dynamic modals with more than one root instance, which is uncommon

Events

NameDescription
before-openEmits while modal is still invisible, but was added to the DOM
openedEmits after modal became visible or started transition
before-closeEmits before modal is going to be closed. Can be stopped from the event listener calling event.cancel() (example: you are creating a text editor, and want to stop closing and ask the user to correct mistakes if the text is not valid)
closedEmits right before modal is destroyed

Example:

 

<template>

  <modal name="example"

         :width="300"

         :height="300"

         @before-open="beforeOpen"

         @before-close="beforeClose">

    <b>{{time}}</b>

  </modal>

</template>

<script>

export default {

  name: 'ExampleModal',

  data () {

    return {

      time: 0,

      duration: 5000

    }

  },

  methods: {

    beforeOpen (event) {

      console.log(event)

      // Set the opening time of the modal

      this.time = Date.now()

    },

    beforeClose (event) {

      console.log(event)

      // If modal was open less then 5000 ms - prevent closing it

      if (this.time + this.duration < Date.now()) {

        event.cancel()

      }

    }

  }

}

</script>

Example with a dynamic modal:

 

<script>

export default {

  name: 'ExampleModal',

  data () {

    return {

      time: 0,

      duration: 5000

    }

  },

  methods: {

    openModal () {

      this.$modal.show({

        template: `<b>{{time}}</b>`,

        props: ['time']

      }, {

        time: this.time

      }, {

        width: 300,

        height: 300

      }, {

        'before-open': this.beforeOpen,

        'before-close': this.beforeClose

      })

    },

    beforeOpen (event) {

      console.log(event)

      // Set the opening time of the modal

      this.time = Date.now()

    },

    beforeClose (event) {

      console.log(event)

      // If modal was open less then 5000 ms - prevent closing it

      if (this.time + this.duration < Date.now()) {

        event.cancel()

      }

    }

  }

}

</script>

This example initializes time variable every time the modal is being opened. And then forbids closing it for the next 5000 ms

Other

Height: "auto"

From v1.2.6 height can be set to "auto". If you want to be able to scroll modal in case it's height exceeds window height - you can set flag scrollable="true".

p.s. scrollable will only work with height="auto".

Example:

 

<modal name="foo" height="auto" :scrollable="true">...</modal>

Auto height:

 

Scrollable content & auto height:

 

Close button

If you want to have a Close (x) button in the top-right corner, you can use "top-right" slot for it. There is deliberately no predefined Close button style - you will have to implement/use your own button.

Example:

 

<template>

  <modal name="foo">

 

    <div slot="top-right">

      <button @click="$modal.hide('foo')">

        ❌

      </button>

    </div>

 

    Hello, ☀️!

 

  </modal>

</template>

Draggable handler

Draggable property can accept not only Boolean but also String parameters. With String value, you can specify a CSS selector to the element which will be a "handler" for dragging.

Example:

 

<modal name="bar" draggable=".window-header">

  <div class="window-header">DRAG ME HERE</div>

  <div>

     Hello, 🌎!

  </div>

</modal>

Overlay background color

If you want to change overlay background color, you can easily do it using CSS.

For all modals:

 

.vm--overlay {

  background: red;

}

For specific modal:

 

.vm--overlay[data-modal="my_modal_name"] {

  background: transparent;

}

Fullscreen

 

<modal name="fs" :adaptive="true" width="100%" height="100%">

Dont forget about close button :)

</modal>

IE support

This plugin uses arrow functions, resize observer and other features of modern after-2008-financial-crisis world.

To be able to use this plugin in IE you need to make sure that you transpile the code preoperty. Please read this stackoverflow: https://stackoverflow.com/questions/56446904/transpiling-es6-for-ie11-with-babel

Check out

Check out my other projects:

Developers

To run an example:

 

# Clone repo 

git clone https://github.com/euvl/vue-js-modal.git

 

# Run unit tests 

npm run unit

 

# Run linter 

npm run lint

 

# Build main library for client & SSR 

cd vue-js-modal

npm install

npm run build

 

# Build and run demo 

cd demo/client_side_rendering

npm install

npm run dev

Unit Testing in Vue 2.0 using Jest

Include the plugin to your <Component>.spec.js.

For example: If you're using the plugin in your Main component, then you should include the plugin to your Main.spec.js file.

import VModal from 'vue-js-modal'

Vue.use(VModal)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值