在store文件下的index.js
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)
// 不能访问this
const store = new Vuex.Store({
// 共享状态
state: {
city: '郑州',
list: [],
username: 'Mike',
notice: [1, 2, 3]
},
actions: {
// action不能直接更改state中的数据,只能通过调用mutations来更改数据
changeCity(ctx, payload) {
console.log('action', payload);
ctx.commit("changeCity", payload)
},
getList({ commit }) {
axios.get("http://localhost:3000/scoreList")
.then(res => {
commit("getList", res.data)
})
},
changeNotice({ commit }, payload) {
commit("changeNotice", payload)
}
},
mutations: {
changeCity(state, payload) {
console.log('mutations', payload);
state.city = payload
},
getList(state, payload) {
state.list = payload
},
changeNotice(state, payload) {
state.notice = payload
},
changeUsername(state, payload) {
state.username = payload
}
},
getters: {
bodyList(state) {
return state.list.filter((item) => {
return item.sex == "男";
});
},
city: state => state.city,
noticeAdmin: state => {
return state.notice.slice(0, 2)
}
}
})
export default store
在组件中使用
<template>
<div class="hello">
<h1>{{ msg }}----数据---{{ city }}----{{ username }}---{{notice}}</h1>
<p><button @click="changeCity('上海');getList()">修改state中的city</button></p>
<!-- <p><button @click="getList">list</button></p> -->
<p>
<button @click="changeNotice([78, 90, 56])">修改state中的notice</button>
</p>
<p>
<button @click="changeUser('Jack')">修改state中的username</button>
</p>
{{ list }}
<hr />
{{ bodyList }}
</div>
</template>
<script>
import { mapState, mapGetters, mapActions, mapMutations } from "vuex";
export default {
name: "HelloWorld",
props: {
msg: String,
},
data() {
return {};
},
// state和getter都通过计算属性获取
computed: {
// city() {
// return this.$store.state.city;
// },
// list() {
// return this.$store.state.list;
// },
// bodyList() {
// return this.$store.getters.bodyList;
// },
//使用辅助函数
...mapState(["city", "list", "username",'notice']),
...mapGetters(["bodyList"]),
},
// actions和mutations都通过methods获取
methods: {
// changeCity() {
// // this.$store.dispatch("changeCity", "北京");
// // 没有异步可以直接使用commit调用mutations
// this.$store.commit("changeCity", "上海");
// // 有异步直接使用dispatch调用actions
// // this.$store.dispatch("getList");
// },
// changeNotice() {
// this.$store.dispatch("changeNotice", [78, 90, 45]);
// },
// changeUsername() {
// this.$store.commit("changeUsername", "Amy");
// },
...mapActions(["changeNotice",'getList']),
// ...mapActions(["getList"]),
...mapMutations(["changeCity"]),
...mapMutations({
changeUser: "changeUsername",
}),
handler() {
console.log(this.city);
},
},
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>