创建api文件夹,在文件夹中创建mockAjax.js,和请求数据的api.js。
import axios from 'axios'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
const requests = axios.create({
// 基础路径
baseURL: '/mock',
// 请求不能超过5S
timeout: 5000
})
requests.interceptors.request.use((config) => {
nprogress.start()
return config
})
requests.interceptors.response.use(
(res) => {
nprogress.done()
return res.data
}
)
export default requests
api/index.js
import mockRequests from './mockAjax'
export const reqgetCategoryList = () => mockRequests.get('/category')
创建mock文件夹,然后创建mockServer.js,用来模拟请求
import Mock from 'mockjs'
import category from './category.json'
Mock.mock('/mock/category', { code: 200, data: category })
在mock文件夹中创建json,表示请求的数据
category.json
[
{
"category_id": "6809637890",
"category_name": "后端"
}
]
创建store文件夹,然后创建index.js
import { reqgetCategoryList } from '@/api'
import { createStore } from 'vuex'
export default createStore({
state: {
categoryList: []
},
getters: {
},
mutations: {
GETCATEGORYLIST (state, categoryList) {
state.categoryList = categoryList
console.log('mutaions', state.categoryList)
}
},
actions: {
async getCategoryList ({ commit }) {
const result = await reqgetCategoryList()
console.log('res', result)
if (result.code === 200) {
commit('GETCATEGORYLIST', result.data)
}
}
},
modules: {
}
})
在页面中测试:
Home.vue
<template></template>
<script>
import { watch, computed } from 'vue'
import { useStore } from 'vuex'
export default {
name: 'HomeView',
components: {
},
setup () {
const store = useStore()
store.dispatch('getCategoryList')
const categoryList = computed(() => store.state.categoryList)
watch(categoryList, (newValue, oldValue) => {
console.log('view', newValue)
}, { immediate: true, deep: true })
return {
categoryList
}
}
}
</script>
标签:category,const,获取数据,nprogress,vue3,import,categoryList,mock
From: https://www.cnblogs.com/mantishell/p/17028845.html