vuex
的基本使用
人生苦短,不提概念,只谈使用
安装 vuex
npm i vuex --S
创建文件
常用的 vuex
文件路径在 store/index.js
中
import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex)
export defaule new Vuex.Stroe({
state: {},
mutations: {},
actions: {},
getters: {}
})
vue
中 state
的使用
state
:vuex
的基本数据,用于存储数据
state: {
list: {}, // 所有的任务列表
input_value: '请输入代办事项', // 输入框的内容
next_id: 5, // 下一个列表项的 id
view_key: 'all'
},
vue 页面中使用
<script>
import { mapState } from "vuex";
export default {
name: "app",
data() {
return {};
},
computed: {
// 数组中实在 store/index.js state 中定义的属性
...mapState(["input_value", "view_key"]),
},
methods: {
getState() {
// 直接调用 state 中的值
this.$store.state.input_value;
},
},
};
</script>
mutation
的基本使用
mutation
同步操作,用于更新 state
中的数据
mutations: {
// list:页面中修改后传递的数据
INIT_LIST(state, list) {
// state 数据存储中的数据,固定形参
state.list = list
},
}
vue 页面中使用
<script>
import { mapMutations } from "vuex";
export default {
name: "app",
data() {
return {};
},
methods: {
...mapMutations(["INIT_LIST"]),
getGetter() {
// 直接调用 action 中的值
this.$store.commit("INIT_LIST", list);
// 或者
this.INIT_LIST(list);
},
},
};
</script>
action
的基本使用
action
异步操作,执行context.commit
提交 mutation
actions: {
GET_LIST(context,data) {
context.commit('INIT_LIST', data)
}
},
vue 页面中使用
<script>
import { mapActions } from "vuex";
export default {
name: "app",
data() {
return {};
},
methods: {
...mapAction(["GET_LIST"]),
getGetter() {
// 直接调用 action 中的值
this.$store.dispatch("GET_LIST", data);
// 或者
this.GET_LIST(data);
},
},
};
</script>
getter
的基本使用
getter
:vuex
中的计算属性
getters: {
// 计算属性
UN_DONE_LENGTH(state) {
return (state.list || []).filter((item) => item.done === false).length
},
// 展示代办类型
INFO_LIST(state) {
let list
switch (state.view_key) {
case 'all':
list = state.list
break
case 'undone':
list = state.list.filter(x => !x.done)
break
case 'done':
list = state.list.filter(x => x.done)
break
}
return list
}
},
vue 页面中使用
<script>
import { mapGetters } from "vuex";
export default {
name: "app",
data() {
return {};
},
computed: {
// 数组中实在 store/index.js getter 中定义的属性
...mapGetters(["INFO_LIST", "UN_DONE_LENGTH"]),
},
methods: {
getGetter() {
// 直接调用 getter 中的值
this.$store.getters.INFO_LIST;
},
},
};
</script>