携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第21天,点击查看活动详情
一。Vuex
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
一般组件通过dispatch调用actions,然后再通过commit调用mutations把结果给到state
import Vue from "vue";
// 导入vuex
import Vuex from "vuex";
Vue.use(Vuex);
// 创建导出全局状态管理对象
export default new Vuex.Store({
// 状态(数据)
state: {},
// 计算属性
getters: {
},
// 异步方法
// 调用actions需要通过dispatch
// 一般进行增加条件判断和发送数据请求
actions: {},
// 同步方法
// 调用 mutatios需要通过commit
// 一般用于最后一步的结果
mutations: {},
// 模块
// 当数据变多,有不同的数据模块,可以通过modules模块管理
modules: {},
});
在main.js
1.computed和getters的用法
①.表达式可以写成$store.state.属性名的形式
<p>姓:{{ $store.state.firstn }}</p>
<p>名:{{ $store.state.lastn }}</p>
<p>姓名:{{ $store.state.firstn }}.{{ $store.state.lastn }}</p>
②. 第二种写法computed和getters
<p>姓:{{ firstname }}</p>
<p>名:{{ lastname }}</p>
<p>姓名:{{ fullname }}</p>
computed:{
fullname() {
return this.$store.getters.fullname;
},
firstname() {
return this.$store.getters.firstname;
},
lastname() {
return this.$store.getters.lastname;
},
}
// 计算属性
getters: {
// getters里面函数有一个参数,state
fullname(state) {
return state.firstn + "." + state.lastn;
},
firstname(state) {
return state.firstn;
},
lastname(state) {
return state.lastn;
},
},
③. 第三种写法computed
<p>姓:{{ fn }}</p>
<p>名:{{fb}}</p>
<p>姓名:{{ fc }}</p>
computed: {
fn() {
return this.$store.state.firstn;
},
fb() {
return this.$store.state.lastn;
},
fc() {
return this.$store.state.firstn + this.$store.state.lastn;
},
}
总结;getters和computed,如果计算出来的结果只有一个组件使用可以用computed,多个组件都要使用的话用getters