veux 入门

import Vue from 'vue'
import Vuex from 'vuex'
import rs from './mutations/mm'

Vue.use(Vuex)
export default new Vuex.Store({
    // 全局状态
    state: {
        num: 22,
        user: {
            username: "张三",
            userage: 20,
        },
        list: []
    },
    // 计算属性
    getters: {
        xuAge(state) {
            return state.user.userage + 1
        }


    },
    // 修改数据,状态的方法
    mutations: {
        upAge(state, p) {

            console.log(p);
            this.state.user.userage++;
            this.state.num += p;
        },
        getContextList(state, payload) {
            state.list = payload
        },
        ...rs



    },
    // 异步修改数据方法
    actions: {
        getjoke(context) {
            let httpUrl = 'https://api.apiopen.top/getJoke?page=1&count=10&type=text'
            fetch(httpUrl).then((res) => {
                console.log(res);
                return res.json()
            }).then((res) => {
                console.log(res);
                // 不能直接修改 this.list = res.result(错误)  需要在mutations 中处理
                console.log("list:", res.result);

                context.commit('getContextList', res.result)


            })

        }

    },
    // vuex 细分模块
    modules: {

    }
})

vx.vue

<template>
    <div id="vx">
     <h1>  vuex test</h1>
     <button @click="addage">add</button>
       {{ $store.state.user.userage }}
         num:{{ num }}
         <h1>{{ $store.getters.xuAge}}</h1>
       
         <ul v-for="(item,index) in $store.state.list" :key="index">
             {{ item.name}}
             <li>
                 {{ item.text}}
             </li>
         </ul>
       
    </div>
</template>
<script>
// 辅助函数
import { mapState,mapMutations,mapGetters,mapActions} from 'Vuex'

export default {
    mounted(){
        // dispatch 触发 actions 方法
        // this.$store.dispatch('getjoke')
        this.getjoke()
       
    },
//  方法
   methods:{
       ...mapMutations(['upAge','getContextList']),
       ...mapActions(['getjoke']),


       addage(){
           console.log(this);
        //     this.$store.commit('upAge',10) 提交到mutations  upAge处理 
        // commit 触发mutations 方法
        //    this.$store.commit('upAge',10)
        this.upAge(2)
       }

   },
    // 计算属性
   computed:{
       ...mapGetters(['xuAge',]),
       ...mapState(['user','num'])

   }
   
    
}
</script>
<style lang="scss">
$width:375;
@function vw($px){
    @return ($px/$width) * 100vw;
}

</style>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值