Search code examples
javascriptbootstrap-tags-inputvue.js

VueJS - Initializing a tagsinput form field that was loaded as part of template or $el attribute?


I'm following the pattern described in the official documentation of loading views using components. One of the components has a form field I need to have a method called .tagsinput() called on since I'm using TagsInput. So, something like $('#tags').tagsinput(). Here's a simplified version of what I'm doing:

  CreateBoardForm = Vue.extend
    template: "<input type='text' v-text='tags' id='tags'/>"
    data:
      tags: ''
    ready: ->
      // this is where I'm hoping to access
      // tags and call $('#tags').tagsinput() on it
      // However, this.$el and this.template are all undefined
      // I was hoping to do something like this.$el.find('#tags').tagsinput()

  Vue.component('CreateBoardForm', CreateBoardForm)

  vue = new Vue(
    el: '#main',
    data:
      currentView: 'createBoardForm'
    components:
      createBoardForm: CreateBoardForm
  )

Any help on how I could possibly initialize that form field would be greatly appreciated.

Thank you


Solution

  • OK, I figured this out. Basically, you have to create a new component, listen to the attached event, use computed properties and then use the v-ref tag which becomes a reference to the tags input. I switched from this tagsinput library to another, but the idea is the same. Here's a working JSFiddle and below is the code:

    <div id="tags-input-example">
        <tags-input v-ref="twitterUsers"></tags-input>
        <input type="button" v-on="click: onSubmit" value="Submit"/>        
    </div>
    
    <script type="text/x-template" id="tags-input">
        <input type="text" />
    </script>
    
    Vue.component('tags-input', {
        template: "#tags-input",
        attached: function() {
            $(this.$el).find('input').tagsInput();
        },
        computed: {
            tags: {
                get: function () {
                    return $(this.$el).find('input').val();
                }
            }    
        }
    });
    
    vm = new Vue({
        el: '#tags-input-example',
        methods: {
            onSubmit: function(e) {
                console.log(this.$.twitterUsers.tags);
                alert("The tags are: " + this.$.twitterUsers.tags);
            }
        }
    });