快速过一遍vuex实际用法
因为这里我有很多组件中使用了axios请求,并且在开发和测试环境中要随时替换地址,所以这个访问地址就比较固定,需要做一个全局变量优化一下,比如这里,我有三个地址,这里依然是她们3个…所以我们需要用一下vuex
安装:vuex,vue2的话一般安装vuex3,vue3安装vuex4,如果出现安装失败情况,去查下自己的vue版本或者vuex版本,相比兼容即可
npm install vuex@3
安装成功后,我们建立一个store.js的文件,目的是与main.js分开管理,我们打开store.js看一下,state是用来声明全局变量的地方,我们在某个组件中使用时要this.$store.state.属性名就行了
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state:{
LocalHostURL:'http://localhost:80',
ServerURL:'http://43.142.56.133:80'
},
mutations: {},
actions: {},
getters: {}
})
export default store
在main中引用
import Vue from 'vue'
import App from './App.vue'
import store from './store'
new Vue({
el: '#app',
store,
render: h => h(App)
})
组件中测试打印
console.log(this.$store.state)