1、添加vuex:
安装依赖,打开终端,执行命令:
yarn add vuex
不能使用install
编码新建utils目录下store.js文件
/**存储*/
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
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文件
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
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
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文件
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://192.168.1.15:8080/api',
ws: true,
changeOrigin: true
},
}
}
}