问题tips:当mixins里面包含异步请求函数,而我们又需要在组件中使用该异步请求函数的返回值时,我们会取不到值,如下
1.mixins中代码
export const myMixin = { data(){ return { num: 1 } }, methods:{ function_one(){ new Promise( (resolve, reject) => { let a = 1; setTimeout( () => { resolve(a) }, 500 ) }).then( res => { console.log( res , 'res'); return res }) } } }
2.组件中的代码
<template> <div class="app-container"> <div class="main"> 这是main </div> </div> </template> <script> import { myMixin } from "./mixins/index.js"; export default { mixins:[myMixin], mounted(){ console.log(this.function_one(), 'main_function_one'); } } </script> <style scoped> .main{ font-size:28px; color:blue; } </style>
3.打印台输出
总结:this.function_one()为undefine
解决方法:不要返回结果而是直接返回异步函数,在组件中调用异步函数,异步函数的then回调函数里面做数据处理
1.mixins中代码
export const myMixin = { data(){ return { num: 1 } }, methods:{ async function_one(){ let result = new Promise( (resolve, reject) => { let a = 1; setTimeout( () => { resolve(a) }, 500 ) }) return result } } }
2.组件中的代码
<template> <div class="app-container"> <div class="main"> 这是main </div> </div> </template> <script> import { myMixin } from "./mixins/index.js"; export default { mixins:[myMixin], mounted(){ this.function_one().then( res => { console.log(res, 'main_function_one'); } ) } } </script> <style scoped> .main{ font-size:28px; color:blue; } </style>