前端——Vue3.0中this的替代方法

本文介绍Vue3中如何替代使用this。由于新的组合式API不再使用this,文章提供了两种替代方法:一种是利用getCurrentInstance()方法获取当前组件实例;另一种推荐方法是通过useStore等组合API直接访问状态管理和路由。

Vue3.0中this的替代方法_周围都是小趴菜的博客-优快云博客_vue3的this中this的替代方法

  • 在vue3中,新的组合式API中没有this,我们可以通过以下方法替代this
  • setup 在生命周期 beforecreate 和 created 前执行,此时 vue 对象还未创建,所以我们无法使用 this

方法一

getCurrentInstance() 方法,获取当前组件的实例,通过 ctx 或 proxy 属性获得当前上下文,从而就能在setup中使用router和vuex

export default {
	setup() {
    	let { proxy } = getCurrentInstance();
    	console.log(proxy)
    }
}

 getCurrentInstance 方法去获取组件实例来完成一些主要功能,在项目打包后,会报错(不推荐使用)

方法二(推荐使用)

import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
export default {
  setup () {
    const store = useStore()
	const route = useRoute()
    const router = useRouter()
    return {
      // 访问 state  函数
      count: computed(() => store.state.count),
      // 访问 getter函数
      double: computed(() => store.getters.double)
	  // mutation
      increment: () => store.commit('increment'),
      // 使用 action
      asyncIncrement: () => store.dispatch('asyncIncrement')
    }
  }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值