vue3没有this怎么办?

编程知识 更新时间:2023-04-23 21:29:21

在vue3中,新的组合式API中没有this,那我们如果需要用到this怎么办?

解决方法:

getCurrentInstance 方法获取当前组件的实例,然后通过 ctxproxy 属性获得当前上下文,这样我们就能在setup中使用router和vuex了

import { getCurrentInstance } from "vue";
export default {
	setup() {
    	let { proxy } = getCurrentInstance();
    	proxy.$axios(...)
    	proxy.$router(...)
    }
}

但是

但是,不建议使用,如果要使用router和vuex,推荐这样用:

import { computed } from 'vue'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
export default {
  setup () {
    const store = useStore()
	const route = useRoute()
    const router = useRouter()
    return {
      // 在 computed 函数中访问 state
      count: computed(() => store.state.count),

      // 在 computed 函数中访问 getter
      double: computed(() => store.getters.double)

	  // 使用 mutation
      increment: () => store.commit('increment'),

      // 使用 action
      asyncIncrement: () => store.dispatch('asyncIncrement')
    }
  }
}

大家不要依赖 getCurrentInstance 方法去获取组件实例来完成一些主要功能,否则在项目打包后,一定会报错的。

更多推荐

vue3没有this怎么办?

本文发布于:2023-04-18 03:49:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/0140e6db048f76938ab1f7cd9456e9d9.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 84761文章数
  • 13695阅读数
  • 0评论数