vue框架中export const多常量添加调用及异步请求Promise对象取值赋值操作
昨天技术群里有个同学工作中遇到的问题:
在config.js(相当于配置文件)文件里多常量异步请求接口数据的调用赋值操作,就是Promise对象取值赋值思路想叉批了,我是主后端的,前端vue不太熟,原理及知识面有点少,所以研究很长时间才搞明白,今天记录一下
我的环境:
windows
node
vue
之前已安装好了,具体教程有兴趣的可以复制过去看看
https://www.zongscan.com/demo333/48.html
启动node环境
D:\nodejs\mytest>cnpm run dev
> [email protected] dev D:\nodejs\mytest
> webpack-dev-server --inline --progress --config build/webpack.dev.conf.js
10% building modules 0/1 modules 1 active ... webpack/hot/dev-server ./src
...
添加路由:
D:\nodejs\mytest\src\router\index.js
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import test from '@/components/test'
Vue.use(Router)
export default new Router({
mode:'history',
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/test',
name: 'test',
component: test
}
]
})
添加创建配置文件
D:\nodejs\mytest\src\components\moduls\config.js
import axios from 'axios';
export const aaa = function(v) { return 1}
export const bbb = function(v) { return 2}
//测试
export const ccc = async url => {
let res = await axios.get('https://www.zongscan.com/indextest?v=123')
return res
}
创建添加单页文件
D:\nodejs\mytest\src\components\test.vue
<template>
<div class="hello">
<h1>{{ msg }}---111</h1>
</div>
</template>
<script>
import {aaa ,bbb ,ccc} from './moduls/config.js'
export default {
name: 'HelloWorld',
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
},
mounted() {
//console.log(ccc().then(res => { console.log(res) }))
//赋值 ccc()返回的是Promise对象
ccc().then(res => {
this.msg = res.data
})
}
}
</script>
好了看看效果图:
相关文章