目录
- Vue3使用this
 - 具体使用如下:
 - 补充:Vue3.0中this的替代方法
 - 方法一
 - 方法二(推荐使用)
 - 总结
 
Vue3使用this
Vue2升级到Vue3,有很大的改变,其中最明显的就是以前的this,在新版本中无法使用了,这是为什么呢?
官方是这样说的:在 setup() 内部,this 不会是该活跃实例的引用(即不指向vue实例),因为 setup() 是在解析其它组件选项之前被调用的,所以 setup() 内部的 this 的行为与其它选项中的 this 完全不同。这在和其它选项式 API 一起使用 setup() 时可能会导致混淆。
因此setup函数中不能使用this。所以Vue为了避免我们错误的使用,直接将setup函数中的this修改成了 undefined
所以想要在Vue3中使用this, Vue为我们提供了getCurrentInstance()方法,这个方法返回了ctx和proxy。
具体使用如下:
<script setup>
    import {getCurrentInstance} from '@vue/runtime-core'
    const currentInstance = ref()
    onMounted(() => {
        /**
         * 此处这样使用时因为Vue3不同于Vue2,在 Vue3的setup中我们是无法访问到this的,所以我们需要借助一个方法,
         * 那就是getCurrentInstance,该方法返回了当前的实例对象
         *
         * 注意!!!!!
         * 不要把该函数当作是optionsApi中来获取 this 使用。
         * 该方法只在 setup、生命周期函数中有效,在方法中是无效的
         * */
        currentInstance.value = getCurrentInstance()
    });
</script>
这样我们就可以借助currentInstance 来完成在Vue2中this的使用场景了
补充:Vue3.0中this的替代方法
- 在vue3中,新的组合式API中没有this,我们可以通过以下方法替代this
 - setup 在生命周期 beforecreate 和 created 前执行,此时 vue 对象还未创建,所以我们无法使用 this
 
方法一
getCurrentInstance() 方法,获取当前组件的实例,通过 ctx 或 proxy 属性获得当前上下文,从而就能在setup中使用router和vuex
import { getCurrentInstance } from "vue";
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')
    }
  }
}

总结
	声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
		
评论(0)