Mi componente vue es así:
<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>Funciona
Pero, todavía usa jquery para obtener y actualizar el texto en el lapso
¿Cómo puedo hacerlo usando vue.js 2?
Leí algunas referencias, que usa watch . Pero todavía estoy confundido para usarlo.
Cambio
const totalNotif = $('#total-notif').text() const totalNotifNew = parseInt(totalNotif) + 1 $('#total-notif').text(totalAllNew)Por
//Set this.totalNotif to 1 if not exist or equals to 0. Else increment by 1 this.totalNotif = (this.totalNotif) ? (this.totalNotif + 1) : 1;Pero no entiendo el código:
computed: { ...mapGetters([ 'totalNotif' ]) },Para mi ejemplo, creo que puedes tener:
export default { mounted() { this.initialMount() }, data() { return { totalNotif: 0 } }, ...En la plantilla, cambiará el intervalo con:
<span v-if="totalNotif > 0" class="badge" id="total-notif" v-text="totalNotif"></span> Esto conectará el span con el valor totalNotif . Entonces, en la parte de VueJs, elimine la parte de jquery, actualice solo los datos totalNotif y automáticamente actualizará el contenido del texto de expansión.
EDITAR Para comprender mejor, la parte del script se convierte en:
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 }) }, } }