Vuex基础

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

 

Vuex的组成:

State:数据仓库(数据的唯一来源,可以用来实例化存储全部数据)

getter:用来获取数据 (用来获取的数据的方法,好比vue的computed,用于获取复杂数据,或者派生出新的数据状态)

Mutation:用来修改数据(Muatation的本质就是一个function,一定是同步操作)

Action:用来提交mutation(用来异步操作,提交mutation,相当于对Mutation再次包装一层)

 

安装vuex

1.安装vuex包,通过npm install vuex

2.创建vuex实例:new Vuex.store()

3.main.js中将vuex实例挂载到vue对象上

 

在main.js中引入vuex,再创建vuex的实例

import Vue from 'vue'
import App from './App.vue'
import Vuex from 'vuex'
Vue.config.productionTip = false


Vue.use(Vuex);
// 实例化vuex实例
const store=new Vuex.Store({
	state:{
		count:0
	},
	mutations:{
		countIncrease(state){
			state.count++;
		}
	}
});

// 把store传递进去:
new Vue({
  store,
  render: h => h(App),
}).$mount('#app')

 如果在谷歌浏览器中安装了vue-detected插件的话,可以在vue面板中的vuex,看到状态

在app.vue中拿到存储的count(this.$store.state.count,或者通过一个计算属性存储起来)

<template>
  <div id="app">
  <!-- vuex中会有一个install方法,在vuex实例初始化的时候会挂载到vue实例上,也就是全局的this上,所以通过this.$store就能拿到了 -->
    <h1>count:</h1>
   <!--  {{this.$store.state.count}} -->
    {{count}}
  </div>
</template>

<script>  
export default{
  name:'app',
  computed:{
    count(){
      return this.$store.state.count;
    }
  }
}
</script>

 通过vuex.store的commit方法提交状态变化

<template>
  <div id="app">
  <!-- vuex中会有一个install方法,在vuex实例初始化的时候会挂载到vue实例上,也就是全局的this上,所以通过this.$store就能拿到了 -->
    <h1>count:</h1>
   <!--  {{this.$store.state.count}} -->
    {{count}}
    <button @click="countIncrease">点击</button>
  </div>
</template>

<script>  
export default{
  name:'app',
  computed:{
    count(){
      return this.$store.state.count;
    }
  },
  methods:{
    countIncrease(){
      // 通过vuexstore实例的commit方法来修改数据
      const v=100;
      this.$store.commit('countIncrease',v)
    }
  }
}
</script>

 到此位置vuex的官方demo就完成了,实现了每次点击增加100的效果,且在vue-detected中能监听到数据的动态变化

posted @ 2019-12-30 15:18  日暮途远i  阅读(104)  评论(0)    收藏  举报