Vue3开发实战02-vue项目添加状态管理Vuex,路由router,以及http请求a

2022-09-21 08:05:32 浏览数 (1)

1、添加vuex:

安装依赖,打开终端,执行命令:

yarn add vuex

不能使用install

在这里插入图片描述在这里插入图片描述

编码新建utils目录下store.js文件

代码语言:javascript复制
/**存储*/
import { createStore } from "vuex"
const state = {
    user: {
        userName: "",
        avtived: false,
        online: false
    }
}

const mutations = {
    setUser(state, data) {
        state.user.userName = data.userName;
        state.user.avtived = data.avtived;
    }
}
const actions = {
    setUser({ commit }, data) {
        // 模拟异步处理
        setTimeout(() => {
            commit("setUser", data);
        }, 3000);
    }
}

const getters = {
    getUser(state) {
        return state.user;
    }
}

export default createStore({
    state,
    mutations,
    actions,
    getters
})

修改main.js,测试store

代码语言:javascript复制
import { createApp } from 'vue'
import App from './App.vue'
import store from './utils/store'
createApp(App).use(store).mount('#app')

//测试store
store.commit("setUser",{userName:'xiao wang'})
console.log(store.getters.getUser)

2、添加router

打开终端 执行命令,添加router依赖

yarn add vue-router

在这里插入图片描述在这里插入图片描述

在utils目录下新建router.js文件

代码语言:javascript复制
import {createRouter,createWebHistory} from "vue-router"
import home from '../components/HelloWorld.vue'

const routes = [{
    path: '/',
    component: home
},{
    path:'/other',
    component: home
}]

export default createRouter({
    history:createWebHistory(),
    routes:routes
})

修改main.js

代码语言:java复制
import { createApp } from 'vue'
import App from './App.vue'
import store from './utils/store'
import router from './utils/router'
//Vue.config.productionTip = false

//createApp(App).use(store).use(router).mount('#app')

const app = createApp(App)
app.use(store)
app.use(router)
app.mount('#app')

3、添加axios:

打开终端添加依赖:axios和vue-axios

yarn add axios vue-axios

在这里插入图片描述在这里插入图片描述

修改main.js

代码语言:yaml复制
import { createApp } from 'vue'
import App from './App.vue'
import store from './utils/store'
import router from './utils/router'
import axios from 'axios'
import VueAxios from 'vue-axios'
//Vue.config.productionTip = false

//createApp(App).use(store).use(router).mount('#app')

const app = createApp(App)
app.use(store)
app.use(router)
app.use(VueAxios,axios)
app.mount('#app')


//测试store
store.commit("setUser",{userName:'xiao wang'})
console.log(store.getters.getUser)
//测试axios
axios.get('http://192.168.1.15:8080/api/upload/file?id=806a89ac32f346378dc228206872ef3f').then((response) => {
    console.log(response)
})

关键语句: app.use(VueAxios,axios)

4、添加代理配置:

在根目录下新建vue.config.js文件

代码语言:swift复制
module.exports = {
    devServer: {
        proxy: {
          '/api': {
            target: 'http://192.168.1.15:8080/api',
            ws: true,
            changeOrigin: true
          },
        }
      }
}

0 人点赞