Git Product home page Git Product logo

vue-js-toggle-button's Introduction

Vue.js toggle/switch button.

Get a coffee

Live demo here

Install

npm install vue-js-toggle-button --save

Import

Import plugin:

import ToggleButton from 'vue-js-toggle-button'

Vue.use(ToggleButton)

OR

Import component:

import { ToggleButton } from 'vue-js-toggle-button'

Vue.component('ToggleButton', ToggleButton)

Use

<toggle-button @change="onChangeEventHandler"/>

<toggle-button v-model="myDataVariable"/>

<toggle-button :value="false"
               color="#82C7EB"
               :sync="true"
               :labels="true"/>

<toggle-button :value="true"
               :labels="{checked: 'Foo', unchecked: 'Bar'}"/>

Properties

Name Type Default Description
value Boolean false Initial state of the toggle button
sync Boolean false If set to true, will be watching changes in value property and overwrite the current state of the button whenever value prop changes
speed Number 300 Transition time for the animation
disabled Boolean false Button does not react on mouse events
color [String, Object] #75C791 If String - color of the button when checked
If Object - colors for the button when checked/unchecked or disabled
Example: {checked: '#00FF00', unchecked: '#FF0000', disabled: '#CCCCCC'}
css-colors Boolean false If true - deactivates the setting of colors through inline styles in favor of using CSS styling
labels [Boolean, Object] false If Boolean - shows/hides default labels ("on" and "off")
If Object - sets custom labels for both states.
Example: {checked: 'Foo', unchecked: 'Bar'}
switch-color [String, Object] #BFCBD9 If String - color or background property of the switch when checked
If Object - colors or background property for the switch when checked/uncheked
Example: {checked: '#25EF02', unchecked: 'linear-gradient(red, yellow)'}
width Number 50 Width of the button
height Number 22 Height of the button
margin Number 3 Space between the switch and background border
name String undefined Name to attach to the generated input field
font-size Number undefined Font size

Events

Name Description
change Triggered whenever state of the component changes.
Contains:
value - state of the object
srcEvent - source click event
input Input event for v-model

SSR

Include plugin in your nuxt.config.js file:

module.exports = {
  plugins: ['~plugins/vue-js-toggle-button']
}

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

import Vue from 'vue'
import Button from 'vue-js-toggle-button'

Vue.use(Button)

Browser compatibility

  • Chrome: 40+
  • Firefox: 25+
  • Safari: 10+
  • IE: 11+

vue-js-toggle-button's People

Contributors

adrianthedev avatar ajhaupt7 avatar aldencolerain avatar analyzeplatypus avatar artem-schander avatar asclepiliz avatar bramver avatar cholowao avatar craigballinger avatar cristiandan avatar dependabot[bot] avatar domnantas avatar euvl avatar frankperez87 avatar jlucaspains avatar kabalage avatar keisukeyamashita avatar lehni avatar mikhailloginov avatar omgimalexis avatar ouraios avatar strateego avatar veebuv avatar victorcazanave avatar xavier avatar xon52 avatar zucchinidev 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vue-js-toggle-button's Issues

How to set custom styles for the button?

.vue-js-switch{

     position: absolute;
     top:40%;
     z-index:1;
}

.vue-js-switch .v-switch-core{
    background-color: #2980b9!important;
}

.vue-js-switch .v-switch-button {
   border-radius: 0px!important;
}

Only the vue-js-switch class worked. Even after using !important, there seems to be no change.

click event

how can I use click event, before changing the value

to stop the event with a return false

How can i use it without webpack?

I want to use it directly like typical javascript files include
<script src="plug-file.js">
Which file i need to include?
Is it possible or not?

Please provide a FontAwesome label example.

I've attempted to use FontAwesome as a label to no avail. I've attempted the following:

<toggle-button :width="80" :height="30" :value="true" :labels="{checked: '<i class="fas fa-arrows-alt-h"></i>', unchecked: 'Bar'}"/>

No matter how I organize/adjust my quotes/double-quotes it incorrectly parses the string and simply outputs a portion of the raw HTML. What am I missing?

Keyboard support?

These are wonderful-looking and the API is super clear, but I was wondering if there were any plans to add keyboard / tabbing support? I noticed you added aria labels (nice!), but it doesn't look like I can tab through them or toggle them via the keyboard.

Global Configuration

It would be really nice if we could specify global settings. For instance, if you want all of your switches to have labels, or globally change the labels to something else.

Thank you very much for the plugin.

Install guide should mention installing SASS

What happens?

ToggleButton's CSS is written in SCSS. (Source here).

ToggleButton fails upon installation if sass-loader has not been installed in the vue-cli build:

 ERROR  Failed to compile with 1 errors                                                                           

This dependency was not found:
./node_modules/vue-js-toggle-button/src/Button.vue
Module not found: Error: Can't resolve 'sass-loader' in '/node_modules/vue-js-toggle-button/src'

What should happen?

  • The docs should mention installing the missing dependencies, as mentioned in the vue-cli docs here: npm install sass-loader node-sass --save-dev

Fix

The docs should be updated with the missing step.

Button gets "out of sync"

Hello,

I use this button to trigger an offer publication status.
So when I use this button, it calls an API to change the state of the publication.

If an errors occurs, it should revert the button to initial position, except it does not.
Please help me out, thanks.

      switchActiveState(offer) {
        console.log(offer.active);  // returns true in this example
        const matchItem = collection.find(this.items, item => item.id === offer.id);
        if (matchItem) {
          axios
            .post('/switch-status....')
            .then((response) => {
              if (response.data.success === true) {
                matchItem.active = response.data.status;
              } else {
                // if we get anything but success true, we change the value back to initial
                matchItem.active = offer.active;
              }
            })
            .catch(() => {
              // if we get any error, we change the value back to initial
              matchItem.active = offer.active;
            })
          ;
        }
      },
<template slot="status" slot-scope="slotProps">
          <toggle-button
            @change="switchActiveState(slotProps.item)"
            :value="slotProps.item.active"
            color="#20aec4"
            :sync="true"
            :labels="false"
          />
</template>

Result in screenshot, after clicking, the active on the object is still true, because there were an error:
plein_ecran_16_12_2017_12_04

BUT the button is "false" instead of true as if the offer is not published.
metadata_title_recruitment_center_team

What am I missing there ?

Server-side rendered app support

I'm using Nuxt.js and server-side rendering, which means there is no document. The webpack module in /dist appears to try to reference document in a few places. I didn't look too much into what it's used for, but it leads to errors when I include this package in my project.

I got around this by taking just the Vue component src/Button.vue for my implementation, but something to consider? 😄

Touch support

When you open a switch on a mobile device, you should be able to change its state with swipe gesture.

Invalid prop: type check failed for prop "width". Expected Number, got String.

Invalid prop: type check failed for prop "width". Expected Number, got String.

Hi, I found this "bug" that I think happens when you are using something like VuexPersistedState to save caches. I've had the same issue when passing props to components.

The workaround I found was allowing 2 types in the props:

 props: {
    width: [String, Number]
}

but I'm not sure, maybe you don't like this solution.

Alternatively you call call the props in the component with a bind and it prevents the error in the console.
toggle-button(@change="collapsed = !collapsed" :value="collapsed" :labels="{checked: 'Collapsed', unchecked: 'Extended'}" color="#7322F7" :sync="true" :height="30" :width="92")

Maybe you have a better solution to this, just thought I'd let you know.
Have a good day.

check all

Hello,
Is there a way to check on when you're in a v-model?
Thank you in advance for your assistance

Add support to change on/off label

Hi,

Would be cool if you add a prop to change dynamically the label of the toggle when is on/off because not always you want the label "on" and "off" in the toggle.

Thanks

Couldn't find preset "latest" relative to directory ...

Hi there!

First of all thank you for creating this open-source vue component. Looking at the demo I see is perfect for my project. However, while trying to install it, I came across to the following error message at my webpack build.

ERROR in ./~/babel-loader/lib!./~/vue-loader/lib/selector.js?type=script&index=0!./~/vue-js-toggle-button/src/Button.vue
Module build failed: Error: Couldn't find preset "latest" relative to directory "/home/vagrant/PycharmProjects/zemlabs/node_modules/vue-js-toggle-button"
    at /home/vagrant/PycharmProjects/zemlabs/node_modules/babel-core/lib/transformation/file/options/option-manager.js:293:19
    at Array.map (native)
    at OptionManager.resolvePresets (/home/vagrant/PycharmProjects/zemlabs/node_modules/babel-core/lib/transformation/file/options/option-manager.js:275:20)
    at OptionManager.mergePresets (/home/vagrant/PycharmProjects/zemlabs/node_modules/babel-core/lib/transformation/file/options/option-manager.js:264:10)
    at OptionManager.mergeOptions (/home/vagrant/PycharmProjects/zemlabs/node_modules/babel-core/lib/transformation/file/options/option-manager.js:249:14)
    at OptionManager.init (/home/vagrant/PycharmProjects/zemlabs/node_modules/babel-core/lib/transformation/file/options/option-manager.js:368:12)
    at File.initOptions (/home/vagrant/PycharmProjects/zemlabs/node_modules/babel-core/lib/transformation/file/index.js:212:65)
    at new File (/home/vagrant/PycharmProjects/zemlabs/node_modules/babel-core/lib/transformation/file/index.js:135:24)
    at Pipeline.transform (/home/vagrant/PycharmProjects/zemlabs/node_modules/babel-core/lib/transformation/pipeline.js:46:16)
    at transpile (/home/vagrant/PycharmProjects/zemlabs/node_modules/babel-loader/lib/index.js:46:20)
    at Object.module.exports (/home/vagrant/PycharmProjects/zemlabs/node_modules/babel-loader/lib/index.js:163:20)
 @ ./~/vue-js-toggle-button/src/Button.vue 7:2-90
 @ ./~/babel-loader/lib!./~/vue-loader/lib/selector.js?type=script&index=0!./frontend/app/components/NewProfileForm.vue
 @ ./frontend/app/components/NewProfileForm.vue
 @ ./~/babel-loader/lib!./~/vue-loader/lib/selector.js?type=script&index=0!./frontend/app/components/ProfileManagement.vue
 @ ./frontend/app/components/ProfileManagement.vue

I have little knowledge about the process webpack and babel do. But searching through internet I found that babel-preset-latest is deprecated in favor of using babel-preset-env (found at this thread).

So, I did the wild guess that if I changed the component .babelrc to use balbe-preset-env, it would work. And it did 😀. But, I'm not sure if I'm missing something and if you have already a way to deal with this. In case this is something to fix, I could make the PR if you want 😅.

Thank you!

Value cannot be a computed property

Hey there! Thanks for the component!
I tried binding a computed boolean property to the :value (using sync) and it did not change the value of it.

Value !== toggle data

I have a personal component for displaying a list of data ...
I use a slot for passing a custom template for lines

each line have a toggle button ... and i listent the 'change' event, if value change, send new value on my api and when api response, call a refresh for new data....

But the toggle isn't reactive ! i don't know why ...
image
image

i use this for refreshing my data :

refresh_data(dataRef, data) {
    if (typeof dataRef !== 'undefined') {
      _.each(data, (value, key) => {
        if (key !== 'id') {
          if (_.isObject(value) && !_.isArray(value)) {
            this.refresh_data(dataRef[key], value);
          } else {
            this.$set(dataRef, key, value);
          }
        }
      });
    }
  },
  async refresh() {
    this.isLoading = true;
    const fn = this.$ajax[this.method];
    await fn(this.uri, this.data, this.config).then((items) => {
      if (items.length < this.items.length) {
        const deletedData = _.differenceWith(this.items, items, (x, y) => x.id === y.id);
        deletedData.forEach((data) => {
          this.$delete(this.items, _.findIndex(this.items, data));
        });
      }
      const updatedData = _.differenceObj(items, this.items, true);
      updatedData.forEach((data) => {
        const dataRef = this.items.find(x => x.id === data.id);
        if (typeof dataRef !== 'undefined') {
          this.refresh_data(dataRef, data);
        } else {
          this.$set(this.items, this.items.length, data);
        }
      });
      this.isLoading = false;
      this.init = true;
    });
  },

and in my render :

 <template slot="tab-list-content" slot-scope="ctx">
          <td class="check">
            <toggle-button
              :width="80"
              :height="30"
              :sync="true"
              :value="ctx.item.item.check !== null"
              :color="{checked: '#16a085', unchecked: '#e74c3c'}"
              :labels="{checked: checkDate(ctx.item.item.check), unchecked: $t('form.pending')}"
              @change="onChangeToggleCheck(ctx.item.item)"
            ></toggle-button>
          </td>
          <td v-if="!companySelected" class="site">{{ ctx.item.item.site_name }}</td>
          <td class="task" :class="checkDeadline(ctx.item.item)">{{ ctx.item.item.text }}</td>
          <td class="date" :class="checkDeadline(ctx.item.item)">{{ ctx.item.item.deadline | moment('Do MMMM') }} </td>
        </template>

Error mounting the component

Hi
I liked your toggle button and thought to implement. However, I got following error while implementing it.
I am using vue 2.3.4, and the error is

[Vue warn]: Failed to mount component: template or render function not defined.

found in

---> <ToggleButton>
       <DsVendorIndex> at /home/ck_gagan/dev/my_projects/vue-apps/test-proj/src/components/ds_vendors/index.vue
         <Hello> at /home/ck_gagan/dev/my_projects/vue-apps/test-proj/src/components/Hello.vue
           <App> at /home/ck_gagan/dev/my_projects/vue-apps/test-proj/src/App.vue
             <Root>

I have added following code in the component that uses toggle button

import ToggleButton from 'vue-js-toggle-button'

and manually imported it using

components: {ToggleButton}

and added

<toggle-button :value="true" :labels="{checked: 'Foo', unchecked: 'Bar'}"/>

where I wanted to display the toggle button,

What have I missed

Vue cannot find `toggle-button`

No matter what I try, Vue doesn't seem to be able to find the component . I'm wondering if the issue is using the name when the plugin calls it ToggleButton. Trying didn't work either, for whatever reason my build just won't pick it up.

Is there a reason to favor distributing this as a vue plugin rather than just a component? Since the plugin literally just declares the component, why not instead let the user import the Button component and then use it how they see fit? That way the end user doesn't have to have this component globally if they're not using it everywhere.

Attach a v-model

Hello @euvl and well done for this nice package.
My question is the following :
Is it possible to bind a v-model to the component ? I would like to access the value of the toggle button.
Or maybe you have an other idea of how I could perform this ?
Thank you

The id is not in the object

I run in a small problem when i have 2-3 toggle buttons with one event function, for example:

<ToggleButton id="id-1" @change="onChangeEventHandler" ></ToggleButton>
<ToggleButton id="id-2" @change="onChangeEventHandler" ></ToggleButton>
<ToggleButton id="id-3" @change="onChangeEventHandler" ></ToggleButton>

export default {
   methods:{
       onChangeEventHandler:function(e){
           //there is no ID in the object
           console.log(e)
       }
   }
}

The returned object from the change event does not return any id.
I had to call to parentElemnt to get the id of the toggle button.

onChangeEventHandler:function(e){
          this[e.srcEvent.target.parentElement.getAttribute('id')] = e.value;
}

Maybe it's me who did something wrong but i couldn't get the id.

Cant't see the toggle-button

And get the following message in my console:
[Vue warn]: Failed to mount component: template or render function not defined. (found in ToggleButton)

tried it with this piece of code:

any ideas?
(Browser: Chrome)

Reset the toggle on a external event

Hi,
I want to change the state of the toggle to false,on clicking a diffrent button, tried by changing the value of the value prop and with sync true, but it doesnt seem to work.

<toggle-button :value=toggleMenu @change="toggleView" 
v-if="toggleShow"  :sync="true" :labels="false"
:width=60 :height=30  ></toggle-button>

on click i am doing
this.toggleMenu = false,
but still it does not reset

Invalid documentation for colors (error compiling template)

Webpack reports Error compiling template: invalid expression: :color="#82C7EB"

for

    <toggle-button
      @change="changeApplyQueueEmmiter"
      :value="false"
      :color="#82C7EB"
      :sync="true"
      :labels="{checked: 'apply', unchecked: 'apply_queue'}"
    />

How the color syntax should be noted ?

Webpack into UMD Module

Thanks for the great component! At the moment this is being installed globally as a plugin, however, it would work better if it was webpacked in to a UMD module so it could be registered on a per-component basis e.g.:

import ToggleButton from 'vue-js-toggle-button'

export default {
  components: {
    ToggleButton
  }
}

I can see there is already a dist folder, however, that still doesn't allow you to register the component individually, I'd be happy to put in a pull-request when I get the chance if you want.

Allow using classes for colors

Was looking today for something like this and it's awesome. Great job @euvl!

Is there a way to use CSS classes to style the colors instead of hard-coding the colors as properties? Would love to be able to use this in a themeable system and give people the ability to make the switch match their theme.

Thanks!

Overflowing

when my contenter display absolute and then height less then 350px, the button will overflow

Microsoft Edge issues

I'm just testing version 1.1.5 with Microsoft Edge 40.15063.0.0 / Microsoft EdgeHTML 15.15063 and all I'm seeing is a circle when off and nothing at all when toggled on.

Same issue just looking http://vue-js-toggle-button.yev.io/

Not sure what's wrong but it's not happy...

Accessibility

Hey!

This component currently doesn't work with screen readers. It seems a pretty easy fix - just make the checkbox element visible to screen readers.

Also, are you fine if I use this library as an example in a talk of an input library which doesn't work with screen readers? It 100% isn't intended as an attack and it won't be the only library I talk about - most libraries in the Vue ecosystem have the same problem!

Ability to increase height and width

This is a beautiful switch, thank you for your efforts. If there could be a way to increase the overall size of the switch, height and width -- perhaps to a size seen in the docs. If this could be controlled through a variable (like 'sm' or 'lg') or other means that would be great. The font size of 10px is a little small for some of my users.

Button state doesn't change on change in v-model programatically

example :

<template>
    <toggle-button
       v-model="state"
       :labels="{checked: 'High', unchecked: 'Low'}"
     />
     <v-btn v-on:click="reset()">Reset</v-btn>
</template>
<script>
  export default {
    data () {
        return {
            state: false
        }
    },
    methods: {
        reset () {
            this.state = false
        }
    }
  }
</script>

When I toggle the button, state is set to true.

When I click on reset button the value of state changes to false but the Toggle Button doesn't show the change.

ezgif com-video-to-gif

Failed to mount component

Hi, I tried to use the plugin for my app with Vue 2 but got a Vue warn like below

[Vue warn]: Failed to mount component: template or render function not defined.
found in ---> <ToggleButton

Already installed the plugin via npm.

Inside vue component:

import ToggleButton from 'vue-js-toggle-button'
export default {
  components: { ToggleButton }
}

Then I use

<toggle-button :value="true" :labels="{checked: 'Foo', unchecked: 'Bar'}"/>

How to use it in Vuejs with SSR (not nuxt)

Hello,
I am trying to use this plugin in vuejs.

Currently, I have following code in app.js

if (process.browser) { const toggleButton = require('vue-js-toggle-button/dist/ssr.index') Vue.use(toggleButton) }

When I call

<toggle-button v-model="private"> </toggle-button>

I am having

[Vue warn]: Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the "name" option.

I don't know know to register it

Thanks

Change event passing key and check state at the same time

Hi Euvl,

First of all thanks for brilliant component ! Very nice look and feel and fully customized.
As for my question:
When you call @change="handler" I've got switch state that was set as true or false.
When you call :key="i" @change="handler(i)" I've got key of the switch in the v-for.

How to combine both to get switch state and key ?

Thanks!

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.