Vuex store 选项将状态从根组件“注入”到每一个子组件中代码

2018-05-18 10:44:00
admin
原创
536
<!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: {
    count: 0
  },
  mutations: {
  	increment: state => state.count++,
    decrement: state => state.count--
  }
})


// 创建一个 Counter 组件
const Counter = {
  template: `<div>
  <p>{{ count }}</p>
  <p>
    <button @click="increment">+</button>
    <button @click="decrement">-</button>
  </p>
</div>`,
  computed: {
    count () {
		return this.$store.state.count
    }
  },
  methods: {
    increment () {
      this.$store.commit('increment')
    },
    decrement () {
    	this.$store.commit('decrement')
    }
  }
}

const app = new Vue({
  el: '#app',
  // 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
  store,
  components: { Counter },
  template: `
    <div class="app">
      <counter></counter>
    </div>
  `
})
</script>
</body>
</html>				
								
				
  • QQ讨论群
  • 关注微信
    • 欢迎咨询
    • 欢迎加入QQ群 16506021
  • 公众号:源宝网络