mapGetters实例

2018-05-18 21:38:00
admin
原创
276
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vuex 测试实例</title>
<script src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script>
<script src="https://cdn.bootcss.com/vuex/2.3.0/vuex.min.js"></script>
</head>
<body>
<div id="app">

</div>

<script>
// make sure to call Vue.use(Vuex) if using a module system

const store = new Vuex.Store({
  state: {
    todos: [], 
  },
  getters: {
    doneTodos: state => {
      return state.todos.filter(todo => todo.done)
    },
	noTodos: state => {
      return state.todos.filter(todo => !todo.done)
    },
	doneTodosCount: (state, getters) => {
    return getters.doneTodos.length
    },
	noTodosCount: (state, getters) => {
    return getters.noTodos.length
    },
  },
  mutations: {
  	 doneAct(state,payload){
		console.log(state)
		state.todos = payload
	 },
     noAct(state,payload){
		console.log(state)
		state.todos = payload
	},
	initAct(state,payload){
		console.log(state)
		state.todos = payload
	}
  }
})

// 创建一个 Sites 组件
const Todos = {
  template: ` <div>已办事{{myDoneTodosCount}},待办{{myNoTodosCount}} <ul>
        <li v-for="(todo, index) in todos">
      待办事项ID:{{ todo.id }}, 事项内容:{{ todo.text }}
    </li>
  </ul><p>
    <!--<button @click="doneAct">已办</button>-->
    <button @click="noAct">未办</button>
  </p></div>`,
  data: function () { 
    return {
      //myDoneTodosCount:0,
	  //myNoTodosCount:0,
	  //todos:this.$store.state.todos,
    }
  },
  
  computed: {
	...Vuex.mapGetters({
      myDoneTodosCount:'doneTodosCount',
      myNoTodosCount:'noTodosCount',
    }),
	...Vuex.mapState({
    todos : state => state.todos,
	})
  },
  created () {
        this.initialization()
  },
  methods: {
	initialization () {
       var initTodos =   [
      { id: 1, text: '起床', done: true },
      { id: 2, text: '上班', done: false },
	  { id: 3, text: '下班', done: false },
      ]
	   this.$store.commit('initAct',initTodos)
	},
    doneAct () {
      this.$store.commit('doneAct',this.$store.getters.doneTodos)
    },
    noAct () {
    	this.$store.commit('noAct',this.$store.getters.noTodos)
    }
  }
}



const app = new Vue({
  el: '#app',
  // 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
  store,
  components: { Todos },
  template: `
    <div class="app">
      <Todos></Todos>
    </div>
  `
})
</script>
</body>
</html>				
								
								
				
文章分类
联系我们
电话: 18902328227
Email: 2689701946@qq.com
QQ: 2689701946
微信: 18902328227
地址: 广州番禺区繁华路
  • 在线客服
  • 关注微信
  • 联系电话
    • 欢迎咨询
    • 欢迎加入QQ群 303257430
  • 公众号:源宝网络
    • 联系电话及微信号 18902328227