vuex基础练习

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>vuex学习</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
    <script src="https://unpkg.com/vuex@3.0.1/dist/vuex.js"></script>

</head>
<body>
<div id="app">
    <h1>vuex的学习</h1>
    <counter></counter>
</div>
<template id="counter">
    <div>
        <h4>{{count}}</h4>
        <p>{{doneTodosCount}}</p>
        <ul>
            <li v-for="item in doneTodos">{{item.text}}</li>
        </ul>
        <p>第二个学习任务是:{{get2.text}}</p>
        <button @click="increment">增加</button>
        <button @click="incrementAsync">异步增加</button>
    </div>
</template>
<script>
const store = new Vuex.Store({
    state: {
        count :0,
        todos: [
            { id: 1, text: '学习vue', done: true },
            { id: 2, text: '学习vuex', done: false }
        ]
    },
    getters: {
        doneTodos: state =>{
            return state.todos.filter(todo=>todo.done);
        },
        doneTodosCount: (state,getters) => {
            return getters.doneTodos.length;
        },
        getTodoById: (state)=>(id)=>{
            return state.todos.find(todo=>todo.id === id);
        }
    },
    mutations: {
        increment (state,{amount}) {
            state.count += amount;
        }
    },
    actions: {
        incrementAsync  ({commit}) {
            setTimeout(()=>{ commit('increment',{
                amount: 5
            }) },1000);
        }
    }
});

Vue.use(store);
const Counter = {
    template: '#counter',
    computed: {
        count() {
            return this.$store.state.count;
        },
        doneTodos() {
            return this.$store.getters.doneTodos;
        },
        doneTodosCount() {
            return this.$store.getters.doneTodosCount;
        },
        get2() {
            return this.$store.getters.getTodoById(2);
        }
    },
    methods: {
        increment() {
            this.$store.commit('increment',{
                amount: 10
            });
        },
        incrementAsync() {
            this.$store.dispatch('incrementAsync')
        }
    }
}

const app = new Vue({
    el: '#app',
    store,
    components: {Counter}
})
</script>
</body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值