Vuex是什么?
VueX 是一個(gè)專門為 Vue.js 應(yīng)用設(shè)計(jì)的狀態(tài)管理架構(gòu),統(tǒng)一管理和維護(hù)各個(gè)vue組件的可變化狀態(tài)(你可以理解成 vue 組件里的某些 data )。
Vue有五個(gè)核心概念,state, getters, mutations, actions, modules。
總結(jié)
state => 基本數(shù)據(jù)
getters => 從基本數(shù)據(jù)派生的數(shù)據(jù)
mutations => 提交更改數(shù)據(jù)的方法,同步!
actions => 像一個(gè)裝飾器,包裹mutations,使之可以異步。
modules => 模塊化Vuex
State
state即Vuex中的基本數(shù)據(jù)!
單一狀態(tài)樹
Vuex使用單一狀態(tài)樹,即用一個(gè)對(duì)象就包含了全部的狀態(tài)數(shù)據(jù)。state作為構(gòu)造器選項(xiàng),定義了所有我們需要的基本狀態(tài)參數(shù)。
在Vue組件中獲得Vuex屬性
•我們可以通過Vue的Computed獲得Vuex的state,如下:
const store = new Vuex.Store({ state: { count:0 }})const app = new Vue({ //.. store, computed: { count: function(){ return this.$store.state.count } }, //..})下面看下vuex操作state對(duì)象的實(shí)例代碼
每當(dāng) store.state.count 變化的時(shí)候, 都會(huì)重新求取計(jì)算屬性,并且觸發(fā)更新相關(guān)聯(lián)的 DOM。
每一個(gè) Vuex 應(yīng)用的核心就是 store(倉(cāng)庫(kù))。
引用官方文檔的兩句話描述下vuex:
1,Vuex 的狀態(tài)存儲(chǔ)是響應(yīng)式的。當(dāng) Vue 組件從 store 中讀取狀態(tài)的時(shí)候,若 store 中的狀態(tài)發(fā)生變化,那么相應(yīng)的組件也會(huì)相應(yīng)地得到高效更新。
2,你不能直接改變 store 中的狀態(tài)。改變 store 中的狀態(tài)的唯一途徑就是顯式地提交 (commit) mutation。這樣使得我們可以方便地跟蹤每一個(gè)狀態(tài)的變化,從而讓我們能夠?qū)崿F(xiàn)一些工具幫助我們更好地了解我們的應(yīng)用。
使用vuex里的狀態(tài)
1,在根組件中引入store,那么子組件就可以通過this.$store.state.數(shù)據(jù)名字得到這個(gè)全局屬性了。
我用的vue-cli創(chuàng)建的項(xiàng)目,App.vue就是根組件
App.vue的代碼
<template> <div id="app"> <h1>{{$store.state.count}}</h1> <router-view/> </div></template><script> import store from '@/vuex/store';export default { name: 'App', store}</script><style></style>在component文件夾下Count.vue代碼
<template> <div> <h3>{{this.$store.state.count}}</h3> </div></template><script> export default { name:'count', }</script><style scoped></style>store.js的代碼
import Vue from 'vue'import Vuex from 'vuex'Vue.use(Vuex);const state = { count: 1}export default new Vuex.Store({ state,})2,通過mapState輔助函數(shù)得到全局屬性
這種方式的好處是直接通過屬性名就可以使用得到屬性值了。
將Component.vue的代碼進(jìn)行改變
<template> <div> <h3>{{this.$store.state.count}}--{{count}}</h3> <h4>{{index2}}</h4> </div></template><script> import { mapState,mapMutations,mapGetters } from "vuex"; export default { name:'count', data:function(){ return { index:10 } }, //通過對(duì)象展開運(yùn)算符vuex里的屬性可以與組件局部屬性混用。 computed:{...mapState(['count']), index2() { return this.index+30; } } , }</script><style scoped></style>總結(jié)
以上所述是小編給大家介紹的vuex操作state對(duì)象的實(shí)例代碼,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)武林網(wǎng)網(wǎng)站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注