- Full-Stack Vue.js 2 and Laravel 5
- Anthony Gore
- 259字
- 2021-07-02 19:57:23
Watchers
So, how can we add/remove classes from thebodyif it's out of Vue's dominion? We'll have to do it the old-fashioned way with the browser's Web API. We need to run the following statements when the modal is opened or closed:
// Modal opens document.body.classList.add('modal-open'); // Modal closes document.body.classList.remove('modal-closed');
As discussed, Vue adds reactive getters and setters to each data property so that when data changes it knows to update the DOM appropriately. Vue also allows you to write custom logic that hooks into reactive data changes via a feature calledwatchers.
To add a watcher, first add thewatchproperty to your Vue instance. Assign an object to this where each property has the name of a declared data property, and each value is a function. The function has two arguments: the old value and new value.
Whenever a data property changes, Vue will trigger any declared watcher methods:
var app = new Vue({ el: '#app' data: { message: 'Hello world' }, watch: { message: function(newVal, oldVal) { console.log(oldVal, ', ', newVal); } } }); setTimeout(function() { app.message = 'Goodbye world'; // Output: "Hello world, Goodbye world"; }, 2000);
Vue can't update thebodytag for us, but it can trigger custom logic that will. Let's use a watcher to update thebodytag when our modal is opened and closed.
app.js:
var app = new Vue({ data: { ... }, watch: { modalOpen: function() { var className = 'modal-open'; if (this.modalOpen) { document.body.classList.add(className); } else { document.body.classList.remove(className); } } } });
Now when you try to scroll the page you'll see it won't budge!
- WebAssembly實(shí)戰(zhàn)
- Vue.js快速入門與深入實(shí)戰(zhàn)
- SEO智慧
- Securing WebLogic Server 12c
- 從0到1:Python數(shù)據(jù)分析
- Cocos2d-x學(xué)習(xí)筆記:完全掌握Lua API與游戲項(xiàng)目開發(fā) (未來書庫)
- PhoneGap:Beginner's Guide(Third Edition)
- NoSQL數(shù)據(jù)庫原理
- Node.js開發(fā)指南
- 貫通Tomcat開發(fā)
- 現(xiàn)代C++語言核心特性解析
- MonoTouch應(yīng)用開發(fā)實(shí)踐指南:使用C#和.NET開發(fā)iOS應(yīng)用
- Mastering VMware vSphere Storage
- Learning RSLogix 5000 Programming
- 新手學(xué)Visual C