vuex-状态管理

2018-02-23  本文已影响15人  幸宇

每一个 Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。Vuex 和单纯的全局对象有以下两点不同:

1.Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。

2.你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。
四个核心概念:

state
getter
mutation(突变)
action 动作
module 模块

mutation 和 action的区别,action可以处理异步请求,比如连接后端的接口
而mutation只能处理同步

状态管理模式,什么是状态管理模式?
new Vue({
  // state
  data () {
    return {
      count: 0
    }
  },
  // view
  template: `
    <div>{{ count }}</div>
  `,
  // actions
  methods: {
    increment () {
      this.count++
    }
  }
})

这个状态自管理应用包含以下几个部分:

state,驱动应用的数据源;
view,以声明方式将 state 映射到视图;
actions,响应在 view 上的用户输入导致的状态变化。

image.png

但是,当我们的应用遇到多个组件共享状态时,单向数据流的简洁性很容易被破坏:

多个视图依赖于同一状态。
来自不同视图的行为需要变更同一状态。
对于问题一,传参的方法对于多层嵌套的组件将会非常繁琐,并且对于兄弟组件间的状态传递无能为力。对于问题二,我们经常会采用父子组件直接引用或者通过事件来变更和同步状态的多份拷贝。以上的这些模式非常脆弱,通常会导致无法维护的代码。

因此,我们为什么不把组件的共享状态抽取出来,以一个全局单例模式管理呢?在这种模式下,我们的组件树构成了一个巨大的“视图”,不管在树的哪个位置,任何组件都能获取状态或者触发行为!

另外,通过定义和隔离状态管理中的各种概念并强制遵守一定的规则,我们的代码将会变得更结构化且易维护。

image.png

应用代码块

main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
// 引入vuex  
import Vuex from 'vuex'
// 使用vuex
Vue.use(Vuex)
Vue.config.productionTip = false
let store=new Vuex.Store({
  state:{
    totalPrice:0
  },
  getters:{
    getTotal(state){
      return state.totalPrice
    }
  },
  mutations:{
    increment(state,price){
      state.totalPrice+=price
    },
    decrement(state,price){
      state.totalPrice-=price
    }
  },
  actions:{
    increase(context,price){
      context.commit('increment',price)
    }
  }
})
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

app.vue
<template>
  <div id="app">
      <img src="./assets/logo.png">
      <h1>{{ msg }}</h1>
      <!-- <router-view/>
      <router-link :to='{path:"/apple/red"}'>Go to applered</router-link>
      <router-link :to='{path:"/apple"}'>Go to apple</router-link>
      <router-link :to='{path:"/banner"}'>Go to banner</router-link> -->
      {{totalPrice}}
      <apple></apple>
      <banner></banner>
  </div>
</template>

<script>
import Apple from './components/apple.vue'
import Banner from './components/banner.vue'

export default {
  components:{Apple,Banner},
  computed:{
    totalPrice(){
      // return this.$store.state.totalPrice
      return this.$store.getters.getTotal
    }
  },
  name: 'App',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

组件apple.vue
<template>
<div>
     <p>
      i am apple
      {{$route.params.id}}
  </p>
   <button @click="addOne">加5</button>
  <button @click="minusOne">减5</button>
  <button @click="getparms">get parms</button>
  <!-- <router-view/> -->
</div>

</template>

<script>
export default {
  name: 'Apple',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App',
      price:5
    }
  },
  methods:{
    getparms:function(){
      return console.log(this.$route.params)
    },
    addOne(){
      this.$store.dispatch('increase',this.price)
    },
    minusOne(){
      this.$store.commit('decrement',this.price)
      
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

上一篇下一篇

猜你喜欢

热点阅读