标签:money compute wait vuex console mit ued ast 数据
import Vue from ‘vue‘
import Vuex from ‘vuex‘
Vue.use(Vuex)
export default new Vuex.Store({
state: { //存放状态
nickname:‘zhangsan‘,
age:20,
gender:‘男‘
},
mutations: {},
actions: {},
modules: {}
})
<div class="home">{{ $store.state.nickname }}</div>
<template>
<div class="home">
{{ nickname }}
</div>
</template>
<script>
export default {
name: ‘home‘,
computed:{
nickname(){
return this.$store.state.nickname
}
}
}
</script>
import {mapState} from ‘vuex‘
export default {
name: ‘home‘,
computed: mapState([‘nickname‘,‘age‘,‘gender‘]) // 可直接使用
}
mapState([‘nickname‘,‘age‘,‘gender‘])
// 类似于
nickname(){return this.$store.state.nickname}
age(){return this.$store.state.age}
gender(){return this.$store.state.gender}
mapState{
nickname: state => state.app.nockname,
age: state => state.app.age
}
import Vue from ‘vue‘
import Vuex from ‘vuex‘
Vue.use(Vuex)
export default new Vuex.Store({
state: { //存放状态
nickname:‘Simba‘,
firstname:‘张‘,
lastname:‘三丰‘,
age:20,
gender:‘男‘,
money:1000
},
getters:{
realname(state){
return state.firstname+state.lastname
},
money_us(state){
return (state.money/7).toFixed(2)
}
},
mutations: {},
actions: {},
modules: {}
})
computed: {
valued (){
return this.value/7
},
...mapGetters([‘name‘, ‘age‘]) // 可直接使用
}
mutations: { //类似于methods
addAge(state,payLoad){
state.age+=payLoad.number
}
}
<div class="home">
<div><button @click="test">测试</button></div>
</div>
methods:{
test(){
// 可通过前台操作触发执行mutations里面的方法
this.$store.commit(‘addAge‘,{
number:5
})
}
}
methods:{
...mapMutations([‘addAge‘])
}
// 或者
methods: {
addAge(payLoad){
this.$store.commit(‘addAge‘,payLoad)
}
}
actions: {
getUserInfo(){
return {
nickname:‘Simba‘,
age:20
}
}
}
// 在actions中定义一个方法:getUserInfo,并且返回一个对象
created(){
var res = this.getUserInfo()
console.log(res)
},
methods:{
...mapActions([‘getUserInfo‘])
}
// mapActions([‘getUserInfo‘]) 相当于以下代码
getUserInfo(){
return this.$store.dispatch(‘getUserInfo’)
}
export default new Vuex.Store({
state: {
nickname: ‘‘,
age:0,
gender: ‘‘,
money:0
},
mutations: {
setUerInfo(state,payLoad){
state.nickname = payLoad.nickname
state.age = payLoad.age
state.gender = payLoad.gender
state.money = payLoad.money
}
},
actions: { //actions没有提供state当参数
async getToken({commit}){
var res = await axios.get(‘/token接口‘)
commit(‘setToken‘,res)
},
async getUserInfo(context){
//context可以理解为它是整个Store的对象.类似于this.$store,
他里面包含了state,getter,mutations,actions
const res = await axios.get(‘/接口url‘)
context.commit(‘setUerInfo‘,res)
//相当于 this.$store.commit,第一个参数是方法名,第二个参数是要传入的数据
context.dispatch(‘getToken‘)
//actions也可以调用自己的其他方法
},
}
})
标签:money compute wait vuex console mit ued ast 数据
原文地址:https://www.cnblogs.com/Yancyzheng/p/12714949.html