Vue3 中使用 Axios 获取用户角色信息 - 示例教程
{"title":"axios.get('http://nn.nncoding.icu:8080/api/user/info')\n .then(response => {\n const roles = response.data.roles;\n console.log(roles);\n })\n .catch(error => {\n console.error(error);\n });\n如何在vue3中使用以上代码内容:在Vue3中使用以上代码,可以在Vue组件的setup
函数中调用axios
库进行网络请求。首先,需要安装axios
库:\n\n\nnpm install axios\n
\n\n然后,在Vue组件中引入axios
库,并在setup
函数中使用axios.get
方法发送网络请求:\n\njavascript\nimport { ref } from 'vue';\nimport axios from 'axios';\n\nexport default {\n setup() {\n const roles = ref([]);\n\n axios.get('http:\/\/nn.nncoding.icu:8080\/api\/user\/info')\n .then(response => {\n roles.value = response.data.roles;\n console.log(roles.value);\n })\n .catch(error => {\n console.error(error);\n });\n\n return {\n roles\n };\n }\n}\n
\n\n在上述代码中,我们使用ref
函数创建了一个响应式变量roles
,然后在网络请求成功后将返回的角色数据赋值给roles.value
,并输出到控制台。最后,将roles
变量作为setup
函数的返回值,以便在模板中使用。\n\n注意:在实际开发中,建议将网络请求封装到一个单独的服务文件或钩子函数中,以便复用和管理。以上代码仅作为示例演示。
原文地址: http://www.cveoy.top/t/topic/pNpS 著作权归作者所有。请勿转载和采集!