一、npm i vuex@3 --save
二、创建仓库
1)在src根目录创建store文件夹,再创文件夹分类不同的模块
changeTitle中的index.js
export default {
namespaced: true,
state: {
a: 'hello',
},
};
modules下的的index.js
import changeTitle from './changeTitle';
export default {
changeTitle,
};
store文件夹中的index.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
import modules from './modules';
export default new Vuex.Store({
modules,
});
2)在main.js, 挂载到VUE中
import Vue from 'vue';
import App from './App.vue';
//1
import store from './store';
Vue.config.productionTip = false;
new Vue({
render: (h) => h(App),
//2
store,
}).$mount('#app');
三、组件如何拿到数据呢?
通过$store.state / computed / ...mapState
<template>
<div>
<div class="s">
组件6:
<!-- 直接通过实例获取 -->
<div>{{ $store.state.changeTitle.a }}</div>
<!-- computed -->
<div>{{ changeTitle.a }}</div>
<!-- ...mapState -->
<div>{{ a }}</div>
</div>
</div>
</template>
<script>
import { mapState } from 'vuex';
export default {
name: '',
components: {},
data() {
return {};
},
computed: {
changeTitle() {
const { a } = this.$store.state.changeTitle;
return { a };
},
// 参数1为modules名称,参数2为modules名称对应模块state的数据
...mapState('changeTitle', ['a']),
},
created() {},
mounted() {
console.log('com6', this.$store);
},
};
</script>
<style lang="less" scoped>
.s {
border: 1px solid red;
}
</style>
四、如何dispatch 派遣改变数据
1. 点击触发change函数,触发派遣 this.$store.dispatch('changeTitle/changeSing', str);
2.使用mapActions;点击触发changeMapaction
<template>
<div>
<div class="s">
组件6:
<!-- 直接通过实例获取 -->
<div>{{ $store.state.changeTitle.a }}</div>
<!-- computed -->
<div>{{ changeTitle.a }}</div>
<!-- ...mapState -->
<div>{{ a }}</div>
<div>
<button @click="change('改了111')">点击改变数据改了111</button>
<button @click="changeMapaction('改了222')">
点击改变数据改了222
</button>
</div>
</div>
</div>
</template>
<script>
import { mapState, mapActions } from 'vuex';
export default {
name: '',
components: {},
data() {
return {};
},
computed: {
changeTitle() {
const { a } = this.$store.state.changeTitle;
return { a };
},
// 参数1为modules名称,参数2为modules名称对应模块state的数据
...mapState('changeTitle', ['a']),
},
methods: {
change(str) {
// console.log('str',this.$store.);
this.$store.dispatch('changeTitle/changeSing', str);
},
// 参数为对象,key为函数,value为 modules名称/modules名称下的函数
...mapActions({ changeTitleMapaction: 'changeTitle/changeSing' }),
},
created() {},
mounted() {
console.log('com6', this.$store);
},
};
</script>
<style lang="less" scoped>
.s {
border: 1px solid red;
}
</style>
export default {
namespaced: true,
state: {
a: 'hello',
},
actions: {
changeSing({ commit }, value) {
//模拟异步
setTimeout(() => {
commit('editTitle', value);
}, 1000);
},
},
// 操作state中的数据
mutations: {
editTitle(state, value) {
state.a = value;
},
editSinger(state, value) {
state.singer = value;
},
},
};