Vue2.7组合式中使用this

本文最后更新于:2023年9月4日 晚上

介绍

这是一个非常不合理的需求,请谨慎观看。。

能在setup的作用域下,在函数内容使用this

使用

main.js中引入

1
import './setThis'

使用this()方法

1
2
3
4
5
6
7
8
9
10
11
12
<script setup>

const toMainPage = function () {
this.$router.push('/main')
}.this()
</script>

<template>
<div>
<button @click="toMainPage">跳转</button>
</div>
</template>

这个函数不能是箭头函数,因为这种方法采用修改this指向实现

关于vue2.7组合式中使用router@3的功能,第二个方法:查看

setThis.js

1
2
3
4
5
import { getCurrentInstance } from 'vue';

Function.prototype.this = function () {
return this.bind(getCurrentInstance().proxy)
}

就是为函数原型添加了一个this方法,内容就是通过使用bind改变this指向后返回新的函数

更多问题

就是关于getCurrentInstance的使用性,详见:查看


Vue2.7组合式中使用this
https://xin-fas.github.io/2023/09/04/Vue2-7组合式中使用this/
作者
Xin-FAS
发布于
2023年9月4日
更新于
2023年9月4日
许可协议