Reputation: 7086
My vue component is like this :
<template>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
aria-expanded="false" :title="...">
...
<span v-if="totalNotif > 0" class="badge" id="total-notif">{{ totalNotif }}</span>
</a>
</li>
</template>
<script>
...
export default {
mounted() {
this.initialMount()
},
...
computed: {
...mapGetters([
'totalNotif'
])
},
methods: {
initialMount() {
Echo.private('App.User.' + window.Laravel.authUser.id).notification((notification) => {
const totalNotif = $('#total-notif').text()
const totalNotifNew = parseInt(totalNotif) + 1
$('#total-notif').text(totalNotifNew )
})
},
}
}
</script>
It works
But, it still use jquery to get and update text on the span
How can I do it using vue.js 2?
I read some references, that it using watch
. But I am still confused to use it
Upvotes: 3
Views: 10195
Reputation: 3276
On the template you will change the span with:
<span v-if="totalNotif > 0" class="badge" id="total-notif" v-text="totalNotif"></span>
This will connect span
with value totalNotif
.
So on VueJs part, remove jquery part, updating only data totalNotif
and automatically will update span text content.
EDIT To better understand, the script part become:
export default {
mounted() {
this.initialMount()
},
data() {
return {
totalNotif: 0
}
},
methods: {
initialMount() {
Echo.private('App.User.' + window.Laravel.authUser.id).notification((notification) => {
this.totalNotif = this.totalNotif + 1
})
},
}
}
Upvotes: 0
Reputation: 4443
Change
const totalNotif = $('#total-notif').text()
const totalNotifNew = parseInt(totalNotif) + 1
$('#total-notif').text(totalAllNew)
By
//Set this.totalNotif to 1 if not exist or equals to 0. Else increment by 1
this.totalNotif = (this.totalNotif) ? (this.totalNotif + 1) : 1;
But I don't understand the code :
computed: {
...mapGetters([
'totalNotif'
])
},
For my example I think you can have :
export default {
mounted() {
this.initialMount()
},
data() {
return {
totalNotif: 0
}
},
...
Upvotes: 0