Vuex的簡單認識


 

一. 什么是vuex?

Vuex是一個專為了vue.js 應用程序開發的狀態管理模式

二.為什么要用vuex?

構建一個大型單頁面應用程序時,Vuex可以更好的幫我們的組件外部更好的統一管理狀態

類似服務端的session(單純的比較)

三.Vuex的核心觀念

  • State

是唯一的數據源

單一狀態樹

 

 

 

  • Getters

通過Getters可以派生一些新的狀態

通過Getters 操作只需要done的屬性

  • Mutations

    更改vuex的store中的狀態的唯一方法提交Mutations

    調用

 

  • Actions

Action提交的是mutation,而不是直接變更狀態

Action可以包含任意異步操作

 

  • Modules

面對復雜的應用程序,當管理的狀態比較多時,我們需要將Vuex的store對象分割成模塊(Modules)

四.Vuex狀態管理

因為是初次寫文章以及是后端開發人員,所以能明白,因為和后端思維是通的,但是無法深刻寫出對其的完整理解,見諒

 

五.使用方法

1.安裝

`npm install Vuex --save`

 

2.引入項目

2.1在src目錄下新建Store.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 ++,
​
    decrement:state => state.count --,
​
  }
​
})

 

 

2.2在main.js 引入該js

import Store from '../src/store/store'

 

2.3 掛載Store

new Vue({
​
  el: '#app',
​
  Store,
​
  router,
​
  components: { App },
​
  template: '<App/>'
​
})

 

2.4 新建Test.vue 並建立對應路由 編寫如下代碼<template>


 
  <div>
​
             
​
                {{ count }}
​
               <p><button @click="incre">+</button>
​
              
​
              </p>
​
               
​
       </div>
</template>
<script>
​
    export default {
​
         methods:{
​
            incre(){
​
              
​
             this.$store.commit('increment')
​
              
​
            },
​
           
​
        },
​
         computed:{
​
           count(){
​
                   console.log(this.$store.state.count);
​
                return this.$store.state.count
​
            },
​
        }
​
   }
​
</script>
<style  scoped></style>

運行結果

 

 

 

 

 

 

后記

通過該vuex示例,了解vuex的常用配置及方法調用。希望對不怎么熟悉vuex的同學快速上手vuex項目有點幫助。

因為沒太多東西,我自己也是剛接觸,本例就不往GitHub扔了,如果嘗試了本例,但是沒有跑起來的小伙伴,可以一起交流下。

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM