生活随笔
收集整理的這篇文章主要介紹了
VueX的store的简单使用心结
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
vuex的特點:
多組件共享狀態: 多個組件使用同一個數據
任何一個組件發生改變, 其他組件也要跟著發生相應的變化
安裝vuex npm install vuex:
創建實例:
import Vuex from
'vuex'
import Vue from
'vue'
Vue
.use(Vuex
)const state
= {name
: '張三',age
: 18
}
const mutations
= {changeName
(state
, params
) {state
.name
= params
.name
},changeAge
(state
, params
) {state
.age
= params
.age
}
}
const actions
= {actionsChangeAge
( context
, params
) {context
.commit('changeAge', params
)}
}
const getters
= {doubleAge
(state
) {return state
.age
* 2}
}const store
= new Vuex
.Store({ state
, mutations
, actions
, getters
})
export
default store# 引入文件:
import Vue from
'vue'
import App from
'./App.vue'
import store from
'./store/index'
Vue
.config
.productionTip
= falsenew
Vue({store
, render
: h
=> h(App
),
}).$
mount('#app')# 模板:
<template
><div
><h2
>組件
</h2
><!-- 組件可以通過this
.$store
.state 獲取store中的數據
-->name
: {{ this
.$store
.state
.name
}} <br
>age
: {{ this
.$store
.state
.age
}}<button @click
="change">修改年齡
</button
></div
>
</template
>
<script
>
export
default {methods
: {change
() {this
.$store
.dispatch('actionsChangeAge', { age
: 120 })},changeName
() {this
.$store
.commit('changeName', { name
: '寶寶', age
: 19})}}
}
</script
>
----------------------------------------------------------------
store
.commit('increment',
{amount
: 10
})
store
.commit({type
: 'increment',amount
: 10
})dispatch:含有異步操作,數據提交至 actions ,可用于向后臺提交數據
this
.$store
.dispatch('isLogin', true
);commit:同步操作,數據提交至 mutations ,可用于讀取用戶信息寫到緩存里
this
.$store
.commit('loginStatus', 1);state 存放基本數據
getters 從state基本數據派生出的數據
(類似vue中的computed
)
mutations Store中更改state數據狀態的唯一途徑
actions 通過dispatch觸發actions
, actions在通過commit觸發mutations。一般用于處理異步操作
modules 模塊化Vuex
總結
以上是生活随笔為你收集整理的VueX的store的简单使用心结的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。