<!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>