2
votes

I am implementing vue.js in an existing project and bound the vue instance on the body tag with an id of "app".

So far so good, jQuery and Vue.js playing along really well. However, the moment I create components all my jQuery bindings within those components are not working anymore.

The bindings in the root instance however are still functioning.

The HTML:

<body id="app">

<button class="button-app" @click="showMessage('app')">APP</button>

<some-component inline-template>
    <div>
        <button class="button-component" @click="showMessage('component')">COMPONENT</button>
    </div>
</some-component>

</body>

The Javascript:

$('.button-app').on('click', function()
{
    console.info('jQuery: app');
});

$('.button-component').on('click', function()
{
    console.info('jQuery: component');
});

var Component = Vue.extend({
    methods: {
        showMessage: function(message)
        {
            console.info('vue.js component: ' + message);
        }
    }
});

new Vue({
    el: '#app',
    methods: {
        showMessage: function(message)
        {
            console.info('vue.js: ' + message);
        }
    },
    components: {
        'some-component': Component
    }
});

Here's a fiddle to show and prove what I described above: https://jsfiddle.net/z7o8wkz7/2/

Is that normal behaviour or can I do something to keep jQuery bindings in components alive?

EDIT:

Since I am using pjax, jquery and vuejs I have solved the correct loading order in the following way:

app.js:

$(document).on('ready pjax:end', function() {

    // init vue.js and load components here

    $(document).trigger('vue:loaded');
});

some-query-file.js:

$(document).on('vue:loaded', function() {

    // bind jquery stuff

});

This makes sure that the jQuery bindings are (re-)evaluated after the pjax has loaded and the vue components have been initialized. Works great!

2

2 Answers

2
votes

When you create a component, Vue.js compiles your template (inline or not) and insert it into the document (lifecycle).

Hence, you should attach the jQuery events after the root instance of Vue or reinitiate them into the ready function, because the component will change the DOM.

Examples

Into the ready function

After the root instance

-1
votes

put jquery code inside the mounted function