Vue2/3中的this

一、Vue3

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')
    }
  }
}

二、Vue2中,为什么this能直接获取到data和methods

通过this能直接获取到methods,是因为在new Vue的时候遍历了methods,为每一个methods方法通过bind指定了this,也就是指定了this为new Vue的实例(vm)。

通过this能直接获取到data,是因为data里的属性最终被存储到new Vue的实例(vm)上的_data对象中,我们访问this.xxx,实际上是访问通过Object.defineProperty代理后的this._data.xxx。

function Person(options) {
    let vm = this;
    vm.$options = options;
    if (options.data) {
        initData(vm);
    }
    if (options.methods) {
        initMethods(vm, options.methods);
    }
}
 
function initData(vm) {
    let data = vm._data = vm.$options.data;
    let keys = Object.keys(data);
    let len = keys.length;
    while(len--) {
        let key = keys[len];
        proxy(vm, "_data", key);
    }
}
 
function proxy(vm, sourceKeys, key) {
    Object.defineProperties(vm, sourceKeys, {
        enumerable: true,
        configurable: true,
        get: function() {
            return vm[sourceKeys][key];
        },
        set: function(val) {
            return vm[sourceKeys][key] = val;
        }
    })
}
 
function initMethods(vm, methods) {
    for (let key in methods) {
        vm[key] = typeof methods[key] === "function" ? methods[key].bind(vm) : noop;
    }
}
 
function noop(a, b, c) { }
 
let p1 = new Person({
    data: {
        name: "pino",
        age: 18
    },
    methods: {
        sayName() {
            console.log("I am" + this.name);
        }
    }
})
 
console.log(p1.name); // pino
p1.sayName(); // 'I am pino'

 

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue.js,this关键字在Vue2和Vue3有不同的使用方式。 在Vue2,this指向Vue实例,可以在Vue组件的方法和生命周期函数使用this来访问Vue实例的属性和方法。例如,在Vue2的methods声明的方法,可以使用this来访问Vue实例的data属性。此外,在Vue2的生命周期函数,this指向当前的Vue实例。 而在Vue3,this被废弃了,不再指向Vue实例。相反,Vue3使用了composition API,其的setup函数是Vue3的主要入口点。在setup函数,无法直接使用this访问Vue实例。相反,您可以使用传递给setup函数的参数来访问Vue实例的属性和方法。 综上所述,Vue2可以使用this来访问Vue实例的属性和方法,而Vue3不再使用this来访问Vue实例,而是使用composition API的方式来操作数据和组件的逻辑。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [vue3与vue2的区别(你不知道细节全在这)](https://blog.csdn.net/weixin_43932097/article/details/121512132)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [vue2和vue3的区别](https://blog.csdn.net/weixin_55903841/article/details/121520103)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值