Code Monkey home page Code Monkey logo

vue-select2's Introduction

[archived]Vue Select2 Component

This project is archived and no longer maintained.

This project was generated with Vue cli version 2.9.1.

Instructions

This project is built for showing how to use v-select2-component.

If you want to use it in Vue 3.0, check vue3-select2-component.

v-select2-component

Source code in: https://github.com/godbasin/vue-select2/tree/npm-publish-code.

Related Versions

Vue-Select2-Component is baseed on these plugins and libs(version):

How to use


Install

// npm install
npm install v-select2-component --save

Use as component

  1. import as global component.
// import Select2Component
import Select2 from 'v-select2-component';

Vue.component('Select2', Select2);
new Vue({
	// ...
})
  1. import into a single component.
// import Select2Component
import Select2 from 'v-select2-component';

<template>
  <div>
    <Select2 v-model="myValue" :options="myOptions" :settings="{ settingOption: value, settingOption: value }" @change="myChangeEvent($event)" @select="mySelectEvent($event)" />
    <h4>Value: {{ myValue }}</h4>
  </div>
</template>
<script>
export default {
    // declare Select2Component
    components: {Select2},
    data() {
        return {
            myValue: '',
            myOptions: ['op1', 'op2', 'op3'] // or [{id: key, text: value}, {id: key, text: value}]
        }
    },
    methods: {
        myChangeEvent(val){
            console.log(val);
        },
        mySelectEvent({id, text}){
            console.log({id, text})
        }
    }
}
</script>

Options

  • options: option[]
    • select options for select2
    • option: {id: key, text: value} or string
  • v-model: option value that is selected
    • id or string while multiple is disable
    • id[] or string[] while multiple is enable
  • disabled
    • if select is disabled
  • settings
    • configurable settings, see Select2 options API
    • setting: { settingOption: value, settingOption: value }

Events

  • change
    • triggered when option selected change
    • return value
    • parmas: same with v-model
  • select
    • triggered when option selected
    • parmas: option({id: value, text: key, selected: ifSelected} or string)
  • open
    • triggered whenever the dropdown is opened
  • close
    • triggered whenever the dropdown is closed
  • clear
    • triggered whenever the dropdown is cleared
  • more events refer to select2 events

vue-select2's People

Contributors

godbasin 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

vue-select2's Issues

width is too short..

why??
screen shot 2018-11-29 at 23 38 05

          <Select2
            class="select2"
            v-model="country"
            :options="myOptions"
            :settings="{ settingOption: value, settingOption: value }"
            @change="myChangeEvent($event)"
            @select="mySelectEvent($event)"
          />

and

.select2 {
  width: 2000px;
}

but never changed...

Dropdown doesn't close when I use more than one select2 on a page

When I use more than one select2 on the same page and toggle between 2 dropdowns, the dropdowns remain open and even if I click on an empty place on the screen, both of them no longer close. When there is more than one select2 on a page, I can open 2 select2 components at the same time. Sure, when I try a few

Question: update selected option from js

H',
I set the selected value through a v-model field from js.
But the currently selected value is not displayed in the widget, event if it is actually in the selected_value field.

Component initialization

<vue-select ref="<myRef>" v-model=selected_value" :settings"<mySettingsFunction>">
</vue-select>

JS Code

export default {
    ...
   data() {
       selected_value: null
    },
    methods: {
        updateSelection(selection) {
            this.selected_value = selection;
        }
    }
} 

selected: true is not working

In the options i'm setting the property 'selected: true'

someData: [ { id: 1, text: 'opt1'}, { id: 2, text: 'opt2', disabled: true }, { id: 3, text: 'opt3', selected: true } ]

Its not setting the selected attribute for that option

Custom options and v-model for global component?

I have created a global component for select2 and used it in many pages.
This is my component:
2021-07-07_09-51-50

And I want the ":options" and "v-model" different for each page but it's only show the original "myOptions" in component. How can I custom name and data for ":options" and "v-model" in each page?

`select` event fired when clear button is clicked

Reproduction:

<template>
  <select2
      ref="select2"
      :settings="settings"
      :value="value"
      @change="onChange"
      @select="onSelect"
      @clear="onClear"
    />
</template>

<script>
import Select2 from 'vue-select2';

export default {
  components: {Select2},

  ...

  methods: {
    onChange(value) {
      // called when item selected and cleared ✅
    },
    
    onClear() {
      // called when item cleared ✅
    },

    onSelect(option) {
      // called when item selected and cleared ❌
      // option === the cleared option
    }
  }
}
</script>

Adding the issue in case there's an easy fix, or to maybe take a look and submit a PR.

Support optgroup?

I want to use "optgroup" but not. Don't know that there is a solution to this problem?

Custom Name Option Not Working

Setting the name field doesnt work:

<Select2 v-model="data.org_id" name="title" id="id" :options="list" :settings="select2Settings" />

This will work if the data uses "text":

list: [ { "id": 1, "text": "one" }, { "id": 2, "text": "two" }, { "id": 3, "text": "three" }, { "id": 4, "text": "four" } ]

But using "name" to set to something else doesnt work:

list: [ { "id": 1, "title": "one" }, { "id": 2, "title": "two" }, { "id": 3, "title": "three" }, { "id": 4, "title": "four" } ]

Event DOM not working

Hi @godbasin.
I am using vue3-select2, Is working But when i try event onchange or oninput or etc, i get message warning
"Component emitted event "select" but it is neither declared in the emits option nor as an "onSelect" prop."

whats wrong? Can you help me? Thanks...

Edit:

When try onselect It's working, sorry my fault.

es5 compiled version

Hi, thanks for your great work. I've run to great trouble with IE11 and edge. can you provide us with es5 compiled version? please

select2 is not a function

Hi,

I am getting the following error all over in the console:

Screen Shot 2019-04-23 at 12 35 45 AM

I have installed the package, and later imported it into a single component. The build is working but getting error during rendering. What could be the reason?

Thanks!

v-model doesn't work

Hi, I am using vue3-select2
v-model

Analyzing the code I saw that there is an error on line 97

mounted() { this.select2 = $(this.$el) .find('select') .select2({ placeholder: this.placeholder, ...this.settings, data: this.options }) .on('select2:select select2:unselect', ev => { this.$emit('update:modelValue', this.select2.val()); this.$emit('select', ev['params']['data']); }); this.setValue(this.value); },

last row should be this.setValue(this.modelValue)

modelValue as Number

I get the following warning when my v-model value is an integer:

Invalid prop: type check failed for prop "modelValue". Expected String | Array, got Number with value 1.

Am i missing a setting or something?

<Select2 :settings="select2Settings" type="number" v-model="assigned_to" :options="users"/>

users: [{
                    id: 1,
                    text: 'MD'
                },
                {
                    id: 2,
                    text: 'CR'
                },
                {
                    id: 3,
                    text: 'IL'
                },
...

Update Readme to show Nuxt implementation

Hi, thanks for this beautiful component.

Just wanted to say, if you could please update the readme file to show how we can implement this component using Nuxt.js. It would really help the beginners who want to learn or try out this component in their Nuxt applications without any hassle.

Thanks!

Problem to popular select

Invalid default value for prop "options": Props with type Object/Array must use a factory function to return the default value.

but the select is being populated correctly.
return_vue

autocomplete not trigger change method

When user autocomplete the field, the change method is not trigger, because when the select2 field have selected some value, it will trigger an alert, but the alert is not showing when the field is filled by autocomplete.

And although the select2 field is selected, but the properties is still null.

Nothing get selected : Preselecting options in an remotely-sourced (AJAX) Select2

Data source is remote but before that i have to pre-select option so it is not working. even when i search it shows option but when i select nothing get selected.

for example :

i am using this method : https://select2.org/data-sources/ajax

data is like this

 [
    {
        id: 0,
        text: 'enhancement'
    },
    {
        id: 1,
        text: 'bug'
    },
    {
        id: 2,
        text: 'duplicate'
    },
    {
        id: 3,
        text: 'invalid'
    },
    {
        id: 4,
        text: 'wontfix'
    }
]

in vue component

<template>
  <div>
    <Select2 v-model="myValue" :options="[{'id' : myValue, 'text' : myText}]" :settings="{ ... ajax(...) }" @change="myChangeEvent($event)" @select="mySelectEvent($event)" />
  </div>
</template>

<script>
export default {
    components: {Select2},
    data() {
        return {
            myValue: '4',
            myText : 'wontfix'
        }
    },
    method: {
        myChangeEvent(val){
           // this.myValue = val // v-model is not working then i have tried this but it is not even working
           console.log(val);
           // return val; // not working
        },
        mySelectEvent(data){
            // this.myValue = data.id // v-model is not working then i have tried this but it is not even working 
            this.myText = data.text
        }
    }
}
</script>

vue3-select2-component modal issue

I am working with vue3-select2-component, it works fine on any page but when things come to bootstrap modal vue3-select2-component does not work fine for it like, no searching, no select option nothing
can you guys help me out how to fix this.
I am struggling on this issue from last couple of days but couldn't found any solution yet
will be waiting some good response from you guys.
Thanks

Passing options with selected attribute true is not making the select to have pre-selected options

Hi, I guess the title describes it enough, but just in case.. I am trying to apply these options to a select

[
  { id: 1, text: 'TRADOS', selected: true },
  { id: 2, text: 'ACROSS', selected: true },
  { id: 3, text: 'WORDFAST' },
  { id: 4, text: 'MemoQ' },
  { id: 5, text: 'Transit' },
  { id: 6, text: 'InDesign', selected: true },
  { id: 7, text: 'Omega' },
  { id: 8, text: 'SDLX' },
  { id: 9, text: 'Memsource' }
]

In result I have the multi select rendered, however, there are no preselected options. In vue dev-tools I can see the options with selected attribute as true. I've seen this line in source code so I expected these options to work by default.

Is there another way to make the plugin accept selected values?
Thank you.

Setting bound value for multiple select.

Trying to pre-select multiple values via the bound value only shows the first element in the array.

`
<Select2 :id="filterObject.domId" :options="dataOptions" :settings="select2Settings" @change="updateValue($event)" :disabled="controlsLocked" :value.sync="setValues" multiple/>

data() {
return {
select2Settings: {
multiple: true
},
dataOptions: [{
id: 1,
text: 'test 1'
},
{
id: 2,
text: 'test 2'
}],
setValues: [1,2]
}
},
`

Triggering select2 methods

Hi there,
How can we trigger methods such as close()?

For example, in select2 documentation, we can do:

$('#mySelect2').select2('open');

I tried to trigger this method by reference to the component element but I had no luck, for example:

this.$refs.select2('close');

and on the component:

<Select2 ref="select2" />

How to set selected option when data source is AJAX?

Say I have an App component, which loads a Parent from an API.

A Parent has a thingId property, so the App component renders a ThingSelector to get that value.

A ThingSelector fetches a paginated list of things from the API and emits a thingId value when an option is selected.

That works, but how would I modify this example to display a selected option when App is refreshed?

I found this problem solved in jQuery here, so I'm wondering how to do it in Vue.

ThingSelector.vue -

<template>
  <select2 
    :value="value" 
    @input="(value) => $emit('input', value)" 
    :settings="settings" />
</template>

<script>
import Select2 from "v-select2-component";

export default {
  components: { Select2 },
  props: ["value"],
  data: () => ({
    settings: {
      ajax: {
        url: `/api/v1/things`,
        dataType: "json",
        data: params => {
          return {
            term: params.term,
            page: params.page || 1,
            pageSize: params.pageSize || 50
          };
        },
        processResults: (data) => {
          return {
            results: data.items.map(({ id, name: text }) => ({ id, text })),
            pagination: {
              more: data.current_page < data.last_page
            }
          };
        }
      }
    }
  })
};
</script>

App.vue

<template>
  <thing-selector v-model="parent.thingId" />
</template>

<script>
export default {
  data: () => ({
    parent: {
       thingId: null
    }
  }),
  async mounted() {
    const { data: parent } = await this.$http.get('/api/v1/parents/1');

    this.parent = parent;
  }
};
</script>

Integration problem with webpack (?)

Hi,

I've installed select2 and vue-select2 both with npm:

$ npm install --save select2
$ npm install --save v-select2-component

I've done a basic setup of a component, I've an error in the build:

ERROR in ./node_modules/v-select2-component/src/Select2.vue?vue&type=script&lang=js& (./node_modules/vue-loader/lib??vue-loader-options!./node_modules/v-select2-component/src/Select2.vue?vue&type=script&lang=js&)
Module not found: Error: Can't resolve 'select2/dist/css/select2.min.css' in '<project_path>/node_modules/v-select2-component/src'
 @ ./node_modules/v-select2-component/src/Select2.vue?vue&type=script&lang=js& (./node_modules/vue-loader/lib??vue-loader-options!./node_modules/v-select2-component/src/Select2.vue?vue&type=script&lang=js&) 10:0-41
 @ ./node_modules/v-select2-component/src/Select2.vue?vue&type=script&lang=js&
 @ ./node_modules/v-select2-component/src/Select2.vue
 @ ./node_modules/vue-loader/lib??vue-loader-options!./vue-components/select-contact.vue?vue&type=script&lang=js&
 @ ./vue-components/select-contact.vue?vue&type=script&lang=js&
 @ ./vue-components/select-contact.vue
 @ ./wizard/wizard.js

So the select2 css is not loaded, but it is present:

 ls node_modules/select2/dist/css/
select2.css select2.min.css

Have you any idea ?
Thanks !

How to disable search

I want to have normal dropdown without search, pls tell me if it is possible to disable it.

ajax load options

Using this component can I load the options via ajax.
I have posted this issue in github link can you reply with example

[Request for change] Move dependencies import to index.js

I think it would be nice to move the external dependencies imports to index.js, instead of the single file component, if this is possible technically. This would allow customized builds.
For example, I'm using a template that heavily customizes the Select2 CSS, by using only partials of the original Select2 CSS source files.
Now, if I want use vue-select2, I have to import the custom CSS separately, which would probably work (haven't tried it yet), but will definitely lead to unnecessary double CSS in size. If the imports were in the index.js, I could import the single file component directly (instead of index.js) and take care of importing the dependencies myself, using the customized CSS in the process. In short - this would give more flexibility to the package.

Vue-Select2 not showing on result

After installing vue3-select2-component with their document when i implementing that. it doesn't show in output on html but i have the html of that in source code

BTW: i'm using inertiajs on Laravel framework

install:

// npm install
npm install vue3-select2-component --save

Use as component:

import {createApp, h} from 'vue'
import BootstrapVue3 from 'bootstrap-vue-3'
import IconsPlugin from 'bootstrap-vue-3'
import {InertiaProgress} from "@inertiajs/progress";
import {createInertiaApp, Head} from '@inertiajs/inertia-vue3'
import {Link} from "@inertiajs/inertia-vue3"
///...
import Select2 from 'vue3-select2-component';

import {createStore} from "vuex"

///...

createInertiaApp({
    resolve: async name => {
        return (await import(`./pages/${name}`)).default;
    },
    setup({el, App, props, plugin}) {
        createApp({render: () => h(App, props)})
            .use(plugin)
            .use(bootstrap)
            .use(BootstrapVue3)
            .use(IconsPlugin)
            .use(VueSweetalert2)
            .component('Link', Link)
            .component('Select2', Select2)
            .mount(el)
    },
    title: title => 'azizam - ' + title
}).then(r => {
});

vuejs page which i want to use into that:

<template>
<Select2 v-model="myValue" :options="myOptions"
         :settings="{ settingOption: value, settingOption: value }"
         @change="myChangeEvent($event)"
         @select="mySelectEvent($event)" />
</template>

<script>
import menubar from "./menubar";
import emulator from "./emulator";
import {mapActions} from "vuex";
import notification from "../../../partials/notification";
export default {
    name: "image",
    data() {
        return {
            caption: '',
            myValue: '',
            myOptions: ['op1', 'op2', 'op3']
        }
    },
    components: {
        menubar,
        emulator,
        notification
    },
    methods: {
        ...mapActions([
            'changeBreadcrumb'
        ]),
        myChangeEvent(val){
            console.log(val);
        },
        mySelectEvent({id, text}){
            console.log({id, text})
        }
    },
    mounted() {
        const payload = {
            title: 'محصولات',
            subTitle: 'ایجاد محصول تک عکس در سامانه'
        };
        this.changeBreadcrumb(payload);
    }
}
</script>

console log:

Warning - slinky.min.js is not loaded. application.js:336:21
[Vue warn]: A plugin must either be a function or an object with an "install" function. vendor.js:10544:17
[Vue warn]: Plugin has already been applied to target app. vendor.js:10544:17

Use of Mutation Events is deprecated. Use MutationObserver instead. content.js:19:11
Source map error: Error: request failed with status 404
Resource URL: http://127.0.0.1:8000/js/vendor.js?id=594b688c9609a79fb52afd907a69c736
Source Map URL: tooltip.js.map

in console as you can see i don't get any error for this component

html source code:

<select2 options="op1,op2,op3" settings="[object Object]"></select2>

and then webpack:

const mix = require('laravel-mix');

mix.js('resources/js/app.js', 'public/js')
    //.sass('resources/scss/app.scss','public/css')
    .extract()
    .vue({
        version: 3,
        options: {
            compilerOptions: {
                isCustomElement: (tag) => ['Select2'].includes(tag),
            },
        },
    })
    .postCss('resources/css/app.css', 'public/css', [
        //
    ])
    .version();

Labels not showing properly, plus the Bootstrap 4 theme ain't working

Hi @godbasin.
I am using vue3-select2, the options data is being loaded, but it doesn't show the labels.

My options data is coming like this:

suppliers:[ {company_name:"Company 1", id:1}, {company_name:"Company 2", id: 2} ]

and the component is like this:

<select2 v-model="supplier_id" :options="suppliers" >

But the labels isn't shown. What should I do to make it work?

Doesn't Show Up in Component

Hello.

For some reason the component simply doesn't show up in my component form.

I've imported it correctly:

import Select2 from 'v-select2-component'

I registered it as a component:

components: {
	Opener,
	Select2,		
},

Then use it in my form:

<Select2 
	class="form-control" 
	v-model="form.material" 
	:options="options" 
	:settings="{ theme: 'bootstrap' }"
	@select="selectMaterial"
</Select2>

Absolutely nothing shows up in the form, and using the Vue inspector tool you can see here that Select2 doesn't exist in the component:

screen shot 2018-11-15 at 10 37 36 am

And when using the search in Vue inspector:

screen shot 2018-11-15 at 10 37 55 am

Any ideas why it would not exist at all?

Yes I'm using Vue 2, this is a production app that runs very well, I just want to swap out a different package with this one ... but it doesn't seem to work.

Thanks.

Autofill - hidden field value not updated

I stumbled upon an issue with the browser's Autofill (all browsers, all platforms):

I have a select2 populated with countries. When I use the autofill feature in the browser the correct value gets displayed (for example "Germany" and the correct <span> with the correct value gets rendered.

However:
It doesn't update my v-model and the hidden input remains an emtpy value. The user then has to select a different option and back to the autofill value to update the v-model.

Any ideas on how to fix/workaround this? I'm under a little pressure to get this working, so any dirty workaround would suffice for now.

@change not working

I checked it in this repository @change="myChangeEvent($event)"

I need to filter options('sorter' in settings work fine) but i can't to get modelValue from 'input' that i type any symbols in. How can i get the first symbols that i typed ? Work only event @select but it is not suitable for this task

<Select2
  value="modelValue"
  @input="(e) => modelValue = e.target.value" //or @change
  :settings="sorter: function (results) {
    return results.filter((item) => item.text.startsWith(modelValue))
  }"
/>

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.