Use Vue with Jquery

Here is a simple example with Vue and how to use Jquery with Vue. Use v-cloak and the according stylesheet, to hide placeholders until the app is loaded. Download the ZIP with the full example here.

But you might not need jquery.

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        [v-cloak] { display: none; }
    </style>
</head>
<body>

<div id="app" v-cloak>
    {{ message }}
</div>

<div id="test">Huhuuu</div>

<div id="app-5" v-cloak>
    <p>{{ message }}</p>
    <button v-on:click="reverseMessage">Reverse Message</button>
</div>

<div class="app" id="app6" v-on:input="save($event)">
    <input class="test5" type="text" v-model="eingabefeld"/>
    {{eingabefeld}}
</div>

<div class="app" id="app7" v-on:input="save($event)">
    <input class="test5" type="text" v-model="eingabefeld"/>
    {{eingabefeld}}
</div>



<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="test.js"></script>
</body>
</html>

JavaScript

Use $(this.$el) to access the DOM via Jquery and do what you want. You can only use this in the mounted function. One important thing: Do not change the DOM with Jquery, because Vue will not know about it.

var app = new Vue({
    el: '#app',
    data: {
        message: 'Hello Vue!'
    }
})


var app5 = new Vue({
    el: '#app-5',
    data: {
        message: 'Hello Vue.js!'
    },
    methods: {
        reverseMessage: function () {
            $('#test').html("Bla");
            this.message = this.message.split('').reverse().join('')
        }
    }
})

// Attach multiple elements
$('.app').each(function(i){
    new Vue({
        el: this,
        data: {
            eingabefeld: '24562456'
        },
        mounted(){
            // Access DOM via JQUERY
            console.log("HTML 1", $(this.$el).html());
        },
        created : function(){

        },
        methods: {
            save: function (event) {

            }
        }
    })
});

Be the first to comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.