请问下,这种封装的js如何操控页面的data数据?谢谢大家?

我在A页面引入了下面这个utils.js,这是一个请求接口

import { post_login } from '@/utils/utils.js'

A页面里有个is_login_button的数据


export default {
    data() {
        return {
            is_login_button:false
        };
    },

utils.js 里有个 请求方法,get_openid({

         code:code
     }).then(res=>{
        
    })

我想当这个请求方法成功后,修改this.is_login_button = true

请问如何去做呢?

阅读 2.4k
3 个回答

将 get_openid() 得到的 promise 返回出去,外部使用时通过 then 来处理,大致过程如下

// utils.js
export function post_login() {
    // ...
    return get_openid({
        code:code
    })
}
import { post_login } from '@/utils/utils.js'

export default {
    data() {
        return {
            is_login_button:false
        };
    },
    methods: {
        login() {
            post_login().then((res) => {
                // 登录成功
                this.is_login_button = true
            })
        }
    }
}

可以给utils.js里面的get_openid函数添加一个回调函数,如下:

getOpenId(code, fn) {
    get_openid({code}).then((res) => {
        fn(res)
    })
}

然后在调用的时候,这么调用,先导入getOpenId这个函数哈

getOpenId(123123, (res) => {
    if (res) {
        this.is_login_button = true
    }
})

为什么不用async/await

try {
await get_openid({code:code})
this.is_login_button = true
} catch {}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题