vuex传参------
index.js
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
use: "gao",
num: 2
},
mutations: {
tongChange(state, n) {
state.use = n
},
tongNum(state) {
state.num += 1
},
//异步 不推荐
yibuNum(state) {
setTimeout(() => {
state.num += 1
}, 3000)
}
},
getters: {
updateNum(state) {
return state.use.toUpperCase()
}
},
actions: {
actionTongNum({
commit
}) {
commit("tongNum")
},
actionYiNum({
commit
}) {
setTimeout(() => {
commit("tongNum")
}, 500)
}
}
})
export default store;
state.
<template>
<div>
<h1>首页页面</h1>
<p>用户名是:{{ $store.state.use }}</p>
<p>用户名是:{{ username1 }}</p>
<p>用户名是:{{ use }}</p>
<p>用户名是:{{ username2 }}</p>
<p>用户名是:{{ username3 }}</p>
</div>
</template>
<script>
import { mapState } from "vuex";
export default {
//获取state
computed: {
username1() {
return this.$store.state.use;
},
...mapState(["use"]),
...mapState({ username2: "use" }),
...mapState({ username3: (state) => state.use }),
},
};
</script>
getters
<template>
<div>
<h3>调用getters</h3>
<p>用户名大写 {{ $store.getters.updateNum }}</p>
<p>用户名 {{ us1 }}</p>
<p>用户名 {{ updateNum }}</p>
<p>用户名 {{ us2 }}</p>
</div>
</template>
<script>
import { mapGetters } from "vuex";
export default {
computed: {
us1() {
return this.$store.getters.updateNum;
},
...mapGetters(["updateNum"]),
...mapGetters({ us2: "updateNum" }),
// ...mapGetters({ us2: () =>{}}),没有-----箭头函数
},
};
</script>
Mutations
<template>
<div>
<h2>调用改变state方法的页面</h2>
<input type="text" v-model="name" />{{ name }}
<button @click="changeUser1">改变用户名1</button>
<button @click="$store.commit('tongChange', name)">改变用户名4</button>
<button @click="tongChange(name)">改变用户名0000</button>
<button @click="tongChange2(name)">改变用户名2</button>
<button @click="tongChange3(name)">改变用户名3</button>
</div>
</template>
<script>
import { mapMutations } from "vuex";
export default {
data() {
return {
name: "",
};
},
methods: {
changeUser1() {
return this.$store.commit("tongChange", this.name);
},
...mapMutations(["tongChange"]),
...mapMutations({ tongChange2: "tongChange" }),
...mapMutations({ tongChange3: (commit, n) => commit("tongChange", n) }),
},
};
</script>
Actions
<template>
<div>
<h1>actions可以异步操作</h1>
<h2>{{ $store.state.num }}</h2>
<div>
<p style="color: red">mutations 同步的方式</p>
<button @click="tongNum1">点击+1 ---同步</button>
<button @click="yibuNum1">点击3秒后+1 ---异步</button>
</div>
<div>
<p style="color: red">actions 异步的方式</p>
<button @click="actionTongNum">点击+1 ---同步</button>
<button @click="actionYiNum">点击3秒后+1 ---异步</button>
<button @click="fn1">点击 触发actions--同步</button>
</div>
</div>
</template>
<script>
import { mapActions,mapMutations } from "vuex";
export default {
methods: {
fn1() {
this.$store.dispatch("actionTongNum");
},
...mapActions(["actionTongNum"]),
...mapActions(["actionYiNum"]),
...mapMutations({"tongNum1":"tongNum"}),
...mapMutations({"yibuNum1":"yibuNum"}),
},
};
</script>