Vue之Vuex狀態管理模式

Vuex
    Vuex是一個專門爲Vue.js應用程序開發的狀態管理模式,它採用幾種式存儲管理應用的全部的組件狀態,並以相應的規則保證狀態以一種可預測的方式變化。Vuex也集成到了Vue官方調式工具devtool extension,提供了諸如零配置的time-travel調式,狀態快照導入導出等高級調試功能。
    雖然Vuex能夠幫助咱們進行管理共享狀態,但也附帶了更多的概念和框架,這須要對短時間和長期效益進行權衡。
    若是你不打算開發大型單頁應用,使用Vuex多是繁瑣冗餘的,一個簡單的應用使用global event bus就足夠需求了,
     安裝
         npm install vuex --save
  在src文件夾下新建一個vuex的文件夾,新建一個index.js
  在main.js中引入組件
    import store from './vuex';//能夠省略/index.js
        new Vue({
          el: '#app',
          router,//引入Vue的路由
          store,//引入Vuex狀態管理文件
          components: { App },
            template: '<App/>',
        })

 

     1.state:單一狀態數,每一個應用將僅僅包含一個store實例。
        this.$store.state.狀態名字
        ...mapState(['title'])
     2.getters:能夠從store中的state中派生出一些狀態
        1.能夠認爲是store的計算屬性
        2.this.$store.getters.計算屬性名字
        3. ...mapGetters(['getFilms'])
     3.mutations:更改Vuex的store中的狀態的惟一方法是提交
        常量的涉及風格
            [SOME_MUTATION](state){
                // mutate state
            }
        必須是同步函數
        this.$store.commit('type','payload')
     4.actions
        1.Action 提交的是mutation,而不是直接變動狀態,
        2.Action 能夠包含任意異步操做
        3.this.$store.dispatch('type','payload')
     5.  樣式
    const store = new Vuex.Store({
        state:{
            count:0
        },
        mutations:{
            increment(state,payLoad){
            }
        },
        actions:{
            
        }
    })
主要文件app.vue的代碼
<template>
  <div id="app">
            <!-- vuex驗證模塊 這裏給keyup事件添加一個修飾後綴符.enter當點擊回車才能觸發-->
        <input type="text" autofocus="autofocus" autocomplete="off" placeholder="打算作什麼" class="txt" @keyup.enter="handleEnter"><br/>
        <router-link to="/all">全部</router-link>
        <router-link to="/computed">完成</router-link>
        <router-link to="/active">未完成</router-link>
    <router-view></router-view>
  <!-- 顯示計算屬性中由getters傳過來的sum值,計算屬性依賴於值,當值變化的時候,計算屬性也跟着變化--> <p>未完成總數{{sum}}</p> </div> </template> <script> import {mapGetters} from 'vuex';//引入mapGetters export default { name: 'App', methods: { handleEnter(ev){ console.log(ev.target.value) this.$store.commit('add',{name:ev.target.value,isChecked:false})//用來提交數據給store,提交類型是add和vuex.js中mutations中的方法名字同樣,提交的數據就是ev.target.value,用v-model來實現雙向數據綁定,子組件all中checkbox的來進行通訊 } }, computed: { ...mapGetters(['sum'])//引入vuex狀態管理getters中的一個方法sum,它返回一個值 }, } </script> <style> /* vuex驗證模塊 */ .txt{outline: none;height: 60px;width: 120px;border-bottom: 1px solid #333} </style>

 

vuex文件夾下的index.js的文件代碼
import Vuex from 'vuex';
import Vue from 'vue';
Vue.use(Vuex);

const store = new Vuex.Store({
    state:{
        list:[]//設置一個空數組,用來存放添加進去的全部的狀態。
    },
    mutations:{
        add:(state,payLoad)=>{//這時它會傳過來狀態state這個對象,還會傳過來真實的payLoad
            //console.log(payLoad)
            state.list.push(payLoad);
        }
    },
    getters:{
        activelist(state){//state表明狀態屬性,isChecked是true 或者 false,用filter方法進行過濾,遍歷當中的屬性值是true或者false,若是是false,則篩選出了未完成的
            return state.list.filter(item => item.isChecked == false)
        },
        completelist(state){//返回一個表明已完成的數組
            return state.list.filter(item => item.isChecked == true)
        },
        sum(state){//返回一個未完成總數
            return state.list.filter(item => item.isChecked == false).length
        },
    },
})
export default store;

而且須要添加幾個組件來練習Vuex狀態管理,router文件夾下的index.js代碼css

import Vue from 'vue'
import Router from 'vue-router'
import All from '@/components/all'
import Active from '@/components/active'
import Computed from '@/components/computed'

Vue.use(Router)

export default new Router({
  
  routes: [
    {
      path: '/all',
      component: All
    },
    {
      path: '/active',
      component: Active
    },
    {
      path: '/computed',
      component: Computed
    },
  ]
})

在components文件夾下添加相應的vue組件,active.vue  all.vue  computed.vue三個組件vue

active.vuevue-router

<template>
  <div>我是未完成組件
      <ul>
        <li v-for="data in activelist"><input type="checkbox" v-model="data.isChecked">{{data.name}}</li>
      </ul>
  </div>

</template>

<script>
import {mapGetters} from 'vuex';
export default {
    name:'active',
    data() {
      return {
        
      }
    },
    computed: {
      ...mapGetters(['activelist'])//用簡寫方式,mapGetters的方法將數據引用出來,將vuex中的index.js的方法名引用進來,所以在當前的頁面就能夠獲取到activelist這個實例
    },
}
</script>

<style>

</style>

all.vuevuex

<template>
  <div>
      all組件
      <ul>
        <!--返回了list實例後,能夠遍歷其中的元素來顯示在這個組件中,list裏面包含了對象name 和 isChecked的屬性 --> <li v-for = "data in list"><input type="checkbox" v-model="data.isChecked"> <!-- 當data.isChecked是true的時候,delTxt這個類樣式就會生效 --> <span :class="{delTxt:data.isChecked}">{{data.name}}</span> </li> </ul> </div> </template> <script> import {mapState} from 'vuex';//引入mapState export default { name:'all', data() { return { } }, computed: { ...mapState(['list'])//包含一個命名爲list的實例 }, } </script> <style lang="scss" scoped> .delTxt{text-decoration: line-through} </style>

computed.vuenpm

<template>
  <div>我是已完成組件
    <ul>
      <li v-for="data in completelist">
        <input type="checkbox" v-model="data.isChecked">
        <span :class="{delTxt:data.isChecked}">{{data.name}}</span></li>
    </ul>
  </div>
</template>

<script>
import {mapGetters} from 'vuex';
export default {
    name:'computed',
    data() {
      return {
        
      }
    },
    computed: {
      ...mapGetters(['completelist'])
    },
}
</script>

<style scoped>
.delTxt{text-decoration: line-through}
</style>
相關文章
相關標籤/搜索