Vue的methods方法中调用另一个方法及this指向问题

1.问题概述

1.在vue方法中调用vue的另一个方法如何调用

this.$options.methods.方法名称();

2.存在的问题
被调用方法中的this指向的不再是vue实例,而是调用方法。

2.解决方案

类似于以下,
onSearch调用了getTableData
在调用时,只需要在onsearch方法中
将vue实例赋值给that
再将that作为参数传入getTabaleData中
getTableData将that作为vue实例使用即可。

methods:{
	onSearch() {
	      console.log(this.searchSelectValue)
	      const that = this
	      this.$options.methods.getTableData(that)
	    },
	getTableData(that) {
	      that.loading = true
	      console.log(that.currentPage)
	      axios({
	        method: 'post',
	        url: 'api/room/search',
	        data: {
	          likeName: that.likeName,
	          searchSelectValue: that.searchSelectValue,
	          currentPage: that.currentPage,
	          pageSize: that.pageSize
	        }
	      }).then(res => {
	        that.tableData = res.data.records
	        that.total = res.data.total
	        that.pages = res.data.pages
	        that.loading = false
	      })
	    }
}
Vue ,我们可以在方法里面调用一个方法。这种方式在开发过程非常常见,可以避免代码重复,提高代码的重用性。 首先,我们需要在 Vue 实例定义我们想要调用方法。例如: ``` methods: { methodA() { // ... }, methodB() { this.methodA(); // ... } } ``` 在这个例子,我们在 methods 选项定义了两个方法 methodA 和 methodB。我们可以看到,在 methodB 调用了另一个方法 methodA 。 在调用一个方法时,我们需要使用 this 关键字来指向当前 Vue 实例,以便能够访问其他方法。 以上是用 Vue 实例声明方法的方式实现调用的另一种方法是,我们可以在组件内声明方法。 例如: ``` <template> <div> <button @click="methodB">Click me!</button> </div> </template> <script> export default { methods: { methodA() { // ... }, methodB() { this.methodA(); // ... } } } </script> ``` 在这个例子,我们使用组件的方式来声明方法。我们可以看到,在 template 使用了一个按钮,当点击按钮时会触发 methodB 方法。在 methodB 调用了 methodA ,这使得代码的可读性和可维护性都得到了极大的提高。 总之,Vue 调用一个方法的方式有很多,最常见的是在 Vue 实例或组件定义方法。在调用一个方法时,我们需要使用 this 关键字指向当前 Vue 实例或组件,以便能够访问其他方法。使用这种方式可以避免代码重复,提高代码的重用性和可读性,让代码更加简洁和优雅。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值