根模块数据操作
步骤一:创建 store/index.js 添加一个 counter变量,并可以继续累加操作
export const state = () => ({
counter: 0
})
export const mutations = {
increment (state) {
state.counter++
}
}
步骤二:在页面中,使用
<template>
<div>
首页 {{counter}}
<input type="button" value="+" @click="increment"/>
</div>
</template>
<script>
import { mapState,mapMutations } from 'vuex'
export default {
computed: {
...mapState(['counter'])
},
methods: {
...mapMutations(['increment'])
},
}
</script>
<style>
</style>
其他模块数据操作
步骤一:创建其他模块 store/book.js
export const state = () => ({
money: 0
})
export const mutations = {
addmoney (state) {
state.money += 5
}
}
步骤二:使用指定模块中的数据
<template>
<div>
首页 {{money}}
<input type="button" value="+" @click="addmoney" />
</div>
</template>
<script>
import { mapState,mapMutations } from 'vuex'
export default {
computed: {
money () {
return this.$store.state.book.money
}
},
methods: {
...mapMutations({
addmoney: 'book/addmoney'
})
},
}
</script>
<style>
</style>
完整vuex模板
// state为一个函数, 注意箭头函数写法
const state = () => ({
user: 'jack'
})
// mutations为一个对象
const mutations = {
setUser(state, value) {
state.counter = value
}
}
// action执行mutation
const actions = {
userAction (context,value){
// 可以发送ajax
context.commit('setUser',value)
}
}
// 获取数据
const getters = {
getUser (state) {
return state.user
}
}
export default {
namespace: true, // 命名空间
state,
mutations,
actions,
getters
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)