解决Vue watch里调用方法的坑
作者:Lg泪光 时间:2024-05-05 09:10:44
这里是说watch调用methods里方法的时候,页面经常会报找不到方法
这个时候一定要在watch里去输出一下this,
看看this包裹的壳是不是多了好多层,所以找不到方法,虽然我到现在还没理解为啥有时候会出现一层或几层壳的问题。
例如
正常情况下用this.functionname()就可以调用了。
但是在一些情况下(现在本人还没找到原因)在控制台输出this的时候你会发现数据经常是这样包裹的a{name},name里面对你的methods还包裹了一层,所以使用方法的时候就会变成 this.a.methods.funtionname()
原因还在找,不过解决办法先记下来。
补充知识:使用 Vue 的最佳做法---不要在“created”和“watch”中调用方法
我就废话不多说了,大家还是直接看代码吧~
watch: {
params: {
handler: function (val, oldVal) {
if (val == '1') {
this.initTableData()
}
},
deep: true
},
property: {
immediate: true,
handler: function (val, oldVal) {
this.initTableData()
},
},
},
Vue开发人员经常犯的一个错误是他们不必要地在created和watch中调用方法。 其背后的想法是,我们希望在组件初始化后立即运行watch。
// 不好的做法 created: () { this.handleChange() }, methods: { handleChange() { // stuff happens } }, watch () { property() { this.handleChange() } }
但是,Vue为此提供了内置的解决方案,这是我们经常忘记的Vue watch属性。
我们要做的就是稍微重组watch并声明两个属性:
1.handler (newVal, oldVal)-这是我们的watch方法本身。
2. immediate: true- 代表如果在 wacth 里声明了之后,就会立即先去执行里面的handler方法,如果为 false就跟我们以前的效果一样,不会在绑定的时候就执行
// 好的做法
methods: {
handleChange() {
// stuff happens
}
},
watch () {
property {
immediate: true
handler() {
this.handleChange()
}
}
}
来源:https://blog.csdn.net/qq_38604499/article/details/81354363
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python3爬虫学习之MySQL数据库存储爬取的信息详解
![](https://img.aspxhome.com/file/2023/4/79634_0s.png)
asp中如何对ip段进行过滤限制
在 Python 中接管键盘中断信号的实现方法
![](https://img.aspxhome.com/file/2023/5/118395_0s.jpg)
Python中栈的详细介绍
960px下的黄金分割
![](https://img.aspxhome.com/file/UploadPic/20097/31/498022_1248973274hhmt-19s.jpg)
Python下应用opencv 实现人脸检测功能
![](https://img.aspxhome.com/file/2023/4/118574_0s.jpg)
Python hashlib模块与subprocess模块使用详细介绍
asp fso删除非空目录的例子
css模拟title和alt的提示效果
![](https://img.aspxhome.com/file/UploadPic/200711/8/2007118131348466s.gif)
Python对象的深拷贝和浅拷贝详解
解决GOPATH在GOLAND中的坑
![](https://img.aspxhome.com/file/2023/0/97170_0s.jpg)