vue手写watch
时间: 2023-10-06 15:14:18 浏览: 172
基于vue手写tree插件的那点事儿
在Vue中,可以手动实现watch功能。手写watch的关键在于定义一个名为watch的函数并将其绑定到Vue实例上。下面是一个简单的手写watch的示例:
```javascript
function watch(obj, prop, callback) {
let value = obj[prop];
Object.defineProperty(obj, prop, {
get() {
return value;
},
set(newValue) {
const oldValue = value;
value = newValue;
callback(newValue, oldValue);
}
});
}
const data = {
cityName: 'shanghai'
};
new Vue({
el: '',
data: data,
created() {
watch(data, 'cityName', (newName, oldName) => {
// 处理数据变化的逻辑
});
}
});
```
在上面的代码中,我们定义了一个名为watch的函数,它接受三个参数:对象obj、属性prop和回调函数callback。函数内部使用了Object.defineProperty方法来监听属性的变化,并在属性发生变化时调用回调函数进行处理。在Vue实例的created生命周期钩子中,我们调用了watch函数来监听data对象的cityName属性,并在属性变化时执行相应的回调函数。通过这种方式,我们实现了手写的watch功能。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* [【Vue】watch的详细⽤法](https://blog.csdn.net/weixin_43900414/article/details/125143642)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *3* [实现一个mini-vue](https://download.csdn.net/download/m0_51431448/88129585)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文