Vue中函数内无法访问ref变量但外部可访问的问题求助
问题分析与解决方案
核心问题
你遇到的是回调函数内this指向偏移的问题:
- 在
forEach中使用普通function时,该函数内部的this不再指向Vue实例,因此无法访问this.items。 - 补充:在Vue3选项式API中,setup返回的ref变量会自动解包,所以外层可以直接用
this.items,不需要加.value。
修正方案
方案1:将forEach回调改为箭头函数(推荐)
箭头函数会继承外层作用域的this,直接指向Vue实例:
methods: { fetchPokemon() { axios({ url: 'https://stoplight.io/mocks/appwise-be/pokemon/57519009/pokemon', method: 'get', timeout: 8000, headers: { 'Content-Type': 'application/json', } }).then(data => { // 用箭头函数替代普通function data.data.forEach((pok: basicPokemon) => { try { this.items.push(pok); // 此处直接用this.items,无需.value } catch(err) { console.log(err); } }); }); } }
方案2:提前保存外层的this
把Vue实例的this存到变量中,在回调里使用这个变量:
methods: { fetchPokemon() { const vm = this; // 保存Vue实例的引用 axios({ url: 'https://stoplight.io/mocks/appwise-be/pokemon/57519009/pokemon', method: 'get', timeout: 8000, headers: { 'Content-Type': 'application/json', } }).then(data => { data.data.forEach(function(pok: basicPokemon){ try { vm.items.push(pok); // 使用提前保存的vm } catch(err) { console.log(err); } }); }); } }
方案3:改用Vue3 Composition API风格(更贴合setup用法)
直接在setup里定义函数,无需依赖methods,彻底避免this的问题:
setup() { const items = ref<basicPokemon[]>([]); const fetchPokemon = async () => { try { const response = await axios({ url: 'https://stoplight.io/mocks/appwise-be/pokemon/57519009/pokemon', method: 'get', timeout: 8000, headers: { 'Content-Type': 'application/json', } }); response.data.forEach((pok: basicPokemon) => { items.value.push(pok); // 直接访问setup内的items变量,无需this }); } catch(err) { console.log(err); } }; return { items, fetchPokemon }; // 返回给模板调用 }
额外注意
原代码的methods写法存在语法错误:methods是对象,内部必须是命名方法,不能直接写执行语句。需要把请求逻辑放在类似fetchPokemon()这样的命名方法里,而非暴露在methods根层级。
内容的提问来源于stack exchange,提问作者Raf Vandelaer
相关产品推荐
相关产品推荐

