概述:
每一个 Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。Vuex 和单纯的全局对象有以下两点不同:
-
-
Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。
-
你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。
- store中 state为属性
- store中 getter为计算属性 store中 mutation用于更改状态
-
- mutation必须是同步函数。
- 采用
store.commit
方法触发
- Action 提交的是 mutation,而不是直接变更状态。
- Action 可以包含任意异步操作。
- Action 通过
store.dispatch
方法触发
应用:
1.依赖安装
npm install vuex --save
2.在src目录下新建文件夹 store,在该文件夹下创建store.js(此用法有报错,见下)
store.js
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
count: 0
},
})
export default store
main.js
import Vue from 'vue' import App from './App' import router from './router' import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' import store from './store' Vue.config.productionTip = false Vue.use(ElementUI); new Vue({ router, store, template: '<App/>', components: { App }, }).$mount('#app')
效果:(./store in ./src/main.js)
解决方案:将store.js更名为index.js
index.vue
<template>
<div class="app-container">
<span>home</span>
</div>
</template>
<script>
export default {
name:'home',
created(){
this.$store.commit('increment');
console.log(this.$store.state.count);
},
}
</script>
效果:
3.store用法2
在store文件夹下新建 一个名为modules文件夹,在此文件夹下创建practice.js
practice.js
/**
* 用于学习store
*/
const practice = {
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
},
}
export default practice
stroe文件下创建getters.js
const getters = {
practice_count: state => state.practice.count,
};
export default getters
store文件夹下创建index.js
import Vue from "vue";
import Vuex from "vuex";
import practice from './modules/practice';
import getters from './getters';
Vue.use(Vuex);
const store = new Vuex.Store({
modules: {
practice
},
getters
});
export default store
store.vue
<template> <div class="app-container"> <div class="title">store-getter用法</div> <div class="padding-xxs">count值:{{practice_count}}</div> <div class="padding-xxs">count值2:{{$store.getters.practice_count}}</div> </div> </template> <script> import {mapGetters} from 'vuex'; export default { name:'vueStoreDemo', data() { return { } }, computed: { ...mapGetters([ 'practice_count' ]) }, created(){ this.$store.commit('increment') }, methods: {}, } </script> <style> .title{ font-size: 14px; padding-left: 20px; color: #333; line-height: 34px; background-color: #F5F5F5; } </style>
效果:
....未完待续
参考资料:https://www.cnblogs.com/yesyes/p/6659292.html
https://www.cnblogs.com/chengkun101/p/7979153.html
https://www.cnblogs.com/wisewrong/p/6344390.html
https://www.cnblogs.com/first-time/p/6815036.html
所有评论(0)