关于VueX
VueX
是适用于在Vue
项目开发时使用的状态管理工具。Vue
为这些被多个组件频繁使用的值提供了一个统一管理的工具——VueX
。在具有VueX
的Vue项目中,我们只需要把这些值定义在VueX中,即可在整个Vue项目的组件中使用。
1. 安装
npm i vuex -s
随后会出来一个store目录 ,在下面新建一个index.js
![](https://img-blog.csdnimg.cn/img_convert/ef8ab3dad3e8569892a04b97fc3b63d2.png)
2. 使用
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
//存放属性就是所要管理的状态
state:{
user:{
userName:'',
passWord:''
},
loginSate:false
}
})
3. 把store挂载到当前项目的Vue实例中去 main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
Vue.config.productionTip = false
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
4. 使用
4.1 store/index.js state里面的自定义的属性
<template>
<div class="mainContainer">
<h2>欢迎登陆{{$store.state.user.userName}}</h2>
</div>
</template>
<script>
export default {
data() {
return {
};
},
};
</script>
4.2 store/index.js 定义 mutations
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state:{
loginSate:false
},
mutations:{
//定义方法修改state定义的属性
checkLogin(state){
state.loginSate = true
}
}
})
4.3 使用store/index.js 下面的mutations下面定义的方法this.$store.commit('定义的方法名称',要传的参数)
<template>
<div class="form-container">
<div class="logo">登录</div>
</div>
</template>
<script>
export default {
name: "HelloWorld",
data(){
return{
isLogin:true
}
},
mouted:{
this.checkLogin();
},
methods: {
// 登陆过直接去首页页面
checkLogin() {
this.$store.commit("checkLogin", this.isLogin);
}
}
};
</script>
4.4 store/index.js 定义 action
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state:{
user:{
userName:'',
passWord:''
},
loginSate:false
},
getters:{
getUserName(state,userName){
state.userName=userName
}
},
mutations:{
changeUserInfo(state,data){
state.user.userName=data.userName
state.user.passWord=data.passWord
state.loginSate=data.loginState
},
checkLogin(state){
state.loginSate = true
}
},
actions:{
changes({ commit }, data){
commit('changeUserInfo', data);
}
}
})
使用
<template>
<div class="form-container">
<div class="logo">登录</div>
</div>
</template>
<script>
export default {
name: "HelloWorld",
data(){
return{
user:{
userName:'',
passWord:'',
loginState:false
},
}
},
mouted:{
this.checkLogin();
},
methods: {
// 登陆过直接去首页页面
checkLogin() {
this.$store.dispatch("changes", this.user);
}
}
};
</script>
store的 模块化 modules
1.模块化思想
首先当项目里面需要使用store的地方增多的时候,所有的变量都写在同一个index.js的state里面可读性会很差。
2. 如何使用store里面modules
2.1. 首先创建一个modules文件夹,在文件夹内创建需要分模块的js文件
2.2. js文件内的文件需要使用const user={ state:{},actions:{},mutations:{} } export.default 对象名
2.3. index.js文件引入 import 声明的名称 from ' js文件地址 '
2.4. 使用就和index.js声明的一样使用 this.$store.state.文件.变量名称 this.$store.commit('方法名',要传入的值)