Vue3无组件单页数据更新失败:useNoms无法正确赋值
问题修复:Vue3无组件模式下API数据绑定单选按钮异常
问题根源
- Axios回调this指向错误:普通函数作为
then/catch回调时,this指向的是回调函数自身,而非Vue实例,导致无法更新grille和errored属性。 - 异步操作顺序错误:
fetchData是异步请求,useNomsFct在mounted里被同步调用,此时API数据还未返回,grille仍是初始空值,条件判断无法生效。
修复方案
1. 修正this指向
将Axios回调的普通函数替换为箭头函数,箭头函数会继承外层Vue实例的this上下文,从而能正确访问和修改组件数据。
2. 确保异步操作顺序
把useNomsFct的调用移到Axios请求成功的then回调中,保证只有当API数据返回并更新grille后,才执行useNoms的赋值逻辑;或者使用async/await语法简化异步流程。
修复后的完整代码
const app = Vue.createApp({ data(){ return { grille: {}, // 初始化为空对象而非空字符串,避免后续访问属性报错 useNoms: "", errored: false } }, async mounted(){ // 使用async/await确保请求完成后再执行赋值逻辑 await this.fetchData(); this.useNomsFct(); }, methods: { async fetchData(){ try { const response = await axios.get("http://myAPI/url"); this.grille = response.data; return this.grille; } catch (error) { console.log(error); this.errored = true; } }, useNomsFct(){ // 增加可选链判断,避免grille未初始化时报错 if(this.grille?.useNoms === "non"){ this.useNoms = "non"; } else { this.useNoms = "oui"; } return this.useNoms; }, }, }); app.mount('#app');
额外优化说明
- 把
grille的初始值从空字符串""改为空对象{},避免访问this.grille.useNoms时因grille是字符串而抛出Cannot read properties of string错误。 - 在
useNomsFct中使用可选链操作符?.,进一步确保当grille为空或未定义时,代码不会报错。
HTML部分无需修改,保持原代码即可:
<script nonce="{{ csp_nonce() }}" src="https://unpkg.com/vue@3/dist/vue.global.js"></script> <script nonce="{{ csp_nonce() }}" src="https://unpkg.com/axios/dist/axios.min.js"></script> <div id="app"> <table> <tbody> <tr> <td> <p><label for="useNoms">Oui</label> <input type="radio" name="useNoms" value="oui" v-model="useNoms"/></p> <p> <label for="useNoms">Non</label> <input type="radio" name="useNoms" value="non" v-model="useNoms"/></p> </td> </tr> </tbody> </table> </div>
内容的提问来源于stack exchange,提问作者Vince
相关产品推荐
相关产品推荐

