vux使用


vue-store模式

vueX

props

$emit

文件結構

  • 應用層級的狀態應該集中到單個store對象中;
  • 提交mutation是更改state的唯一方法,且這個過程是同步的;
  • 異步邏輯都應該封裝在action里
    vuex.png

vuex使用步驟

// 引入Vue、Vuex三方件
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
const store = new Vuex.Store({
  modules: {
    user,
    search
  },
  getters
})

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

vuex基本概念:

state:單一狀態樹

嚴格模式

  • 嚴格模式下,state發生變化且不是mutation觸發,則會報錯
  • 便於state所有變更狀態被調試工具跟蹤
  • 深度監聽:生產環境不可使用(strict: process.env.NODE_ENV !== 'production')
const store = new Vuex.Store({
  // ...
  strict: true
})

處理form表單雙向綁定過程中修改vuex中state

方案一:input中模擬雙向綁定
<input :value="message" @input="updateMessage">
computed: {
  ...mapState({
    message: state => state.obj.message
  })
},
methods: {
  updateMessage (e) {
    this.$store.commit('updateMessage', e.target.value)
  }
}
方案二:計算屬性中采用getter + setter方式
<input v-model="message">
computed: {
  message: {
    get () {
      return this.$store.state.obj.message
    },
    set (value) {
      this.$store.commit('updateMessage', value)
    }
  }
}

命名空間

插件機制

export default function createWebSocketPlugin (socket) {
  return store => {
    socket.on('data', data => {
      store.commit('receiveData', data)
    })
    store.subscribe(mutation => {
      if (mutation.type === 'UPDATE_DATA') {
        socket.emit('update', mutation.payload)
      }
    })
  }
}

const plugin = createWebSocketPlugin(socket)

const store = new Vuex.Store({
  state,
  mutations,
  plugins: [plugin]
})

mapState:輔助函數

作用:當一個組件需要獲取多個狀態時候,將這些狀態都聲明為計算屬性會有些重復和冗余。
import { mapState } from 'vuex'

export default {
  // ...
  computed: {
    localComputed () { /* ... */ },
    ...mapState({
        // 箭頭函數可使代碼更簡練
        count: state => state.count,
    
        // 傳字符串參數 'count' 等同於 `state => state.count`
        countAlias: 'count',
    
        // 為了能夠使用 `this` 獲取局部狀態,必須使用常規函數
        countPlusLocalState (state) {
          return state.count + this.localCount
        }
     }) 
  }
}

getter

作用:類似state的計算屬性,用於對state進行二次加工,eg:filter
const store = new Vuex.Store({
  state: {
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false }
    ]
  },
  getters: {
    doneTodos: state => {
      return state.todos.filter(todo => todo.done)
    }
  }
})

獲取:this.$store.getters.doneTodosCount

mapGetters:輔助函數

import { mapGetters } from 'vuex'

export default {
  // ...
  computed: {
  // 使用對象展開運算符將 getter 混入 computed 對象中
    ...mapGetters([
      'doneTodosCount',
      'anotherGetter',
      // ...
    ])
  }
}

// mapGetters取別名
mapGetters({
  // 把 `this.doneCount` 映射為 `this.$store.getters.doneTodosCount`
  doneCount: 'doneTodosCount'
})

Mutation (同步提交)

作用:改變state狀態值的唯一方法是提交mutation
注意:mutation 必須是同步函數
const store = new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    increment (state,payload) {
      // 變更狀態
      state.count += payload.amount
    }
  }
})

// 提交方式(10,稱為載荷)
store.commit('increment', {
    amount:10
})

mapMutation

作用:將組件中的 methods 映射為 store.commit 調用(需要在根節點注入 store)
import { mapMutations } from 'vuex'

export default {
  // ...
  methods: {
    ...mapMutations([
      'increment', // 將 `this.increment()` 映射為 `this.$store.commit('increment')`

      // `mapMutations` 也支持載荷:
      'incrementBy' // 將 `this.incrementBy(amount)` 映射為 `this.$store.commit('incrementBy', amount)`
    ]),
    ...mapMutations({
      add: 'increment' // 將 `this.add()` 映射為 `this.$store.commit('increment')`
    })
  }
}

action(異步提交)

作用:異步提交mutation,並非直接修改state狀態
const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    increment (context) {
      context.commit('increment')
    }
  }
})

dispatch(分發)

作用:異步提交action載荷

store.dispatch('incrementAsync', {
  amount: 10
})

Modules

const moduleA = {
  state: { count: 0 },
  mutations: {
    increment (state) {
      // 這里的 `state` 對象是模塊的局部狀態
      state.count++
    }
  },

  getters: {
    doubleCount (state) {
      return state.count * 2
    }
  }
}

const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

store.state.a // -> moduleA 的狀態
store.state.b // -> moduleB 的狀態

命名空間


免責聲明!

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



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