我的vue组件是这样的:
<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>
有效
但是,它仍然使用 jquery 来获取和更新跨度上的文本
如何使用 vue.js 2 做到这一点?
我读了一些参考资料,它使用了
watch
。但我还是很困惑如何使用它
改变
const totalNotif = $('#total-notif').text()
const totalNotifNew = parseInt(totalNotif) + 1
$('#total-notif').text(totalAllNew)
由
//Set this.totalNotif to 1 if not exist or equals to 0. Else increment by 1
this.totalNotif = (this.totalNotif) ? (this.totalNotif + 1) : 1;
但我不明白代码:
computed: {
...mapGetters([
'totalNotif'
])
},
对于我的例子,我认为你可以:
export default {
mounted() {
this.initialMount()
},
data() {
return {
totalNotif: 0
}
},
...
在模板上,您将使用以下方法更改跨度:
<span v-if="totalNotif > 0" class="badge" id="total-notif" v-text="totalNotif"></span>
这会将
span
与值 totalNotif
连接起来。
所以在VueJs部分,删除jquery部分,只更新数据totalNotif
并自动更新span文本内容。
编辑 为了更好地理解,脚本部分变为:
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
})
},
}
}