vue中使用vuex (mutations)
一、适合初学者使用,保存数据以及获取数据
1、在store文件夹,新建个index.js文件(命名看个人习惯,如果没有该文件夹,可以新建一个,当然也可以不建文件夹,直接新建个js文件也是可以的)
在新建的js文件中写入如下代码:
import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex);
export default new Vuex.Store({
state:{
pathName: "",
}
mutations:{
// 保存当前菜单栏的路径
savePath(state,pathName){
state.pathName = pathName;
},
}
})
2、main.js引用:(注意路径即可)
// 引入vuex-store
import store from './store/index';
new Vue({
el: '#app',
router,
store,
render: h => h(App)
})
3、在组件中保存数据:
methods:{
click(){
// 点击按钮进行一些操作,然后保存数据
this.$store.commit('saveCurrDbSource',this.db)
}
}
4、获取变量:(当数据初始获取不到时,可以使用计算属性用来获取)
this.$store.state.变量名
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。也就是说,前面两个都是状态值本身,mutations才是改变状态的执行者。
注意:mutations只能是同步地更改状态。
vue中使用vuex (actions)
Action 提交的是 mutation,而不是直接变更状态. Action 是异步的,mutation是同步的。
1.在store.js 中 代码为:
import Vue from 'vue'
import Vuex from 'vuex'
//使用vuex模块
Vue.use(Vuex);
//声明静态常量为4
const state = {
count : 4
};
const mutations = {
add(state,n){
state.count +=n.a;
},
sub(state){
state.count--;
}
};
const actions = {
//2种书写方式
addplus(context){ //可以理解为代表了整个的context
context.commit('add',{a:10})
},
subplus({commit}){
commit('sub');
}
};
//导出一个模块
export default new Vuex.Store({
state,
mutations,
actions
})
2.在组件中使用dispatch
template>
<div id="app">
<div id="appaaa">
<h1>这是vuex的示例</h1>
<p>组件内部count{{count}}</p>
<p>
<button @click = "addplus">+</button>
<button @click = "subplus">-</button>
</p>
</p>
</div>
</div>
</template>
<script>
export default {
methods: {
addplus(){
this.$store.dispatch("addplus");第一个参数为action里方法,第二个为要传的参数
},
subplus() {
this.$store.dispatch("subplus")
}
}
}
</script>
高级映射写法
<template>
<div id="app">
<div id="appaaa">
<h1>这是vuex的示例</h1>
<p>组件内部count{{count}}</p>
<p>
<button @click = "addplus">+</button>
<button @click = "subplus">-</button>
</p>
</p>
</div>
</div>
</template>
<script>
//引入mapGetters
import {mapState,mapMutations,mapGetters,mapActions} from 'vuex'
export default {
name:'app',
data(){
return {
}
},
computed:{
...mapState([
"count" 代替:this.$store.state.count;
]),
},
methods:{
...mapActions([
"addplus",// 将 `this.addplus()` 映射为 `this.$store.dispatch('addplus')`
"subplus"
])
}
}
</script>