?watch?監(jiān)聽對象屬性
在 Vue.js 中,使用 `watch` 監(jiān)聽對象屬性的變化時,應(yīng)該將屬性名作為字符串傳遞給 `watch` 選項。
示例如下:
```javascript文章來源:http://www.zghlxwxcb.cn/news/detail-707381.html
watch: { ? 'addform.isCheck1': function(newValue) { ? ? console.log(newValue); ? ? var quantity = this.addform.quantity; ? ? if (quantity % 2 === 0) { ? ? ? quantity = quantity / 2; ? ? } else { ? ? ? quantity = (quantity - 1) / 2; ? ? } ? ? this.updateAddChuZhenForm("上午", quantity, newValue); ? }, ? 'addform.isCheck2': function(newValue) { ? ? var quantity = this.addform.quantity; ? ? if (quantity % 2 === 0) { ? ? ? quantity = quantity / 2; ? ? } else { ? ? ? quantity++; ? ? ? quantity = quantity / 2; ? ? } ? ? this.updateAddChuZhenForm("下午", quantity, newValue); ? } },
updateAddChuZhenForm函數(shù)
//檢查數(shù)組中是否已存在具有相同 sign 標(biāo)識的對象。如果存在,它會更新對象的選中狀態(tài);如果不存在,它會添加一個新對象。如果取消選中,它會在數(shù)組中查找并刪除相應(yīng)的對象。 updateAddChuZhenForm(sign, quantity, isChecked) { console.log(quantity); const existingIndex = this.addChuZhenForm.findIndex( (obj) => obj.sign === sign ); if (isChecked) { if (existingIndex === -1) { this.addChuZhenForm.push({ department_id: this.addform.department_id, room_id: this.addform.room_id, doctor_id: this.addform.doctor_id, inquiry_time: this.addform.inquiry_time, quantity: quantity, sign: sign, }); } } else { if (existingIndex !== -1) { this.addChuZhenForm.splice(existingIndex, 1); } } },
現(xiàn)在,當(dāng) `isCheck1` 或 `isCheck2` 的值發(fā)生變化時,相應(yīng)的 `watch` 函數(shù)將被觸發(fā)。
```
watch監(jiān)聽data變量
如果你想要監(jiān)聽一個普通變量,而不是 Vue 實例的屬性,你可以使用 `watch` 選項以及直接在 `data` 中聲明這個變量。
比如:如果你想監(jiān)聽一個名為 `variableToWatch` 的變量,可以這樣做:
```javascript
data() { ? return { ? ? // 其他的data屬性 ? ? variableToWatch: false, ? }; }, watch: { ? variableToWatch(newValue) { ? ? // 在這里可以處理變量變化的邏輯 ? ? console.log('變量的值變?yōu)椋?, newValue); ? } },
在上述例子中,我們在 `data` 中聲明了一個變量 `variableToWatch`,并在 `watch` 選項中監(jiān)聽了它的變化。當(dāng) `variableToWatch` 的值發(fā)生變化時,相應(yīng)的 `watch` 函數(shù)將被觸發(fā)。
```
如果你希望在組件加載后就立即監(jiān)聽該變量,你可以在 `created` 生命周期鉤子中手動調(diào)用一次 `watch` 函數(shù):
```javascript
created() { ? this.$watch('variableToWatch', (newValue) => { ? ? console.log('變量的值變?yōu)椋?, newValue); ? }); }
這樣,在組件創(chuàng)建后,`variableToWatch` 的初始值也會被監(jiān)視。
```文章來源地址http://www.zghlxwxcb.cn/news/detail-707381.html
到了這里,關(guān)于在 Vue.js 中,使用 watch 監(jiān)聽data變量如:對象屬性/data變量的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!