Vuex学习总结(2)

2.状态管理

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">      
        <style></style>
        <script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
    </head>
    <body>
        <div id="app">
            <button @click="increment">加一</button> {{count}}
        </div>
        <script>
		/*
			状态管理模式
			状态(state)驱动视图(view)
			动作(actions)是通过视图改变状态的方式(用户输入)
		*/
			new Vue({
				data() {
					return {
						count: 0
					}
				},				
				methods: {
					increment() {
						this.count++
					}
				}
			}).$mount('#app')
        </script>
    </body>
</html>

共享状态的简单方法就是将状态写在组件外面。

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">      
        <style>
            
        </style>
        <script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
    </head>
    <body>
		<div id="app">
			<button-counter></button-counter>
			<button-counter></button-counter>
			<button-counter></button-counter>
		</div>
        <script>
			var buttonCounterData = {
				count: 0
			}
			// 定义一个名为 button-counter 的新组件
			Vue.component('button-counter', {
				data: function () {
					return buttonCounterData
				},
				template: '<button v-on:click="count++">点击了 {{ count }} 次.</button>'
			});

			new Vue({ el: '#app' });
        </script>
    </body>
</html>

相关阅读:Vue.js — 组件基础

3.Vuex入门

// store/index.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++
    },
  },
  actions: {
  },
  modules: {
  }
})
<!-- Counter.vue -->
<template>
    <div>
        <button @click="increment">加一</button> {{count}}
    </div>
</template>

<script>
    export default {
        name: "Counter",
        computed: {
            count() {
                return this.$store.state.count
            }
        },
        methods: {
            increment() {
                this.$store.commit('increment')
            }
        }
    }
</script>

<style scoped>

</style>
<!-- About.vue -->
<template>
  <div class="about">
    <h1>This is an about page</h1>
    {{$store.state.count}}
  </div>
</template>

这里在Counter组件提交Vuex的mutations

Vuex入门的示例代码已上传至GitHub仓库:https://github.com/gorgeous-h/vuex-demo1/tree/master
添加Octotree扩展程序,可以将Github项目代码以树形格式展示。

原文地址:https://www.cnblogs.com/gzhjj/p/14348006.html