# Vue & JS 筆記
## Vuex
### state
```
state: {
age: 18
}
```
### mutations
更新 state 內容
```
updateUsername(state, username) {
state.username = username
}
```
### actions
以下兩種情境放在 actions 內
* 呼叫 async 的內容
```
async register({ commit, state, rootState, dispatch, rootGetters } registerData) {
let response = await fetch('/v2.0/users/add', {
body: registerData,
method: 'post'
})
if (response.status != 204) {
let res_msg = await response.json()
commit('updateRegisterMsg', res_msg)
return false
}
return true
}
```
* 用 commit 呼叫 mutations,使 mutations 去更新 states 內容
* 用 dispatch 呼叫 actions
```
authenticate({ commit }, username, password) {
commit('authenticate', token, expiration)
}
```
若要 commit, dispatch 其他 Module 內的 mutations actions,則要加上 { root: true}
`dispatch('connection/UpdateSessionId', auth, { root: true })`
state
等同於 self,表示該 module
rootState
等同於整個 store 的 state
`rootState.othermodule.statename`
rootGetters
等同於整個 store 的 getter
`rootState.othermodule.gettername`
### getters
在 vue component 內獲得 state 內的變數
類似 computed,可以放入邏輯再return
```
login_alert(state) {
return state.login_failed_msg != null
}
```
直接在 components 內使用
this.$store.commit('modulename/mutations', ...)
this.$store.dispatch('modulename/mutations', .....)
this.$store.state.modulename.somestate
this.$store.getters['modulename/mutations']
`import { mapActions, mapGetters } from 'vuex'`
### mapState
### mapGetters
mapState, mapGetters 一般放在 components 內的 computed 內
### mapMutations
### mapActions
mapMutations, mapActions 一般放在 components 內的 methods 內
```
--------------------------
aaa.js
export default AAA = {
namespaced: true,
state: {....},
mutations: {.....},
actions: {.........},
getters: {......}
}
bbb.js
export default BBB = {
namespaced: true,
state: {....},
mutations: {.....},
actions: {.........},
getters: {......}
}
-------------------------
index.js
import AAA from './aaa'
import BBB from './bbb'
Vue.use(Vuex)
export default new Vuex.Store({
state: {},
mutations: {},
modules: {
aaa: AAA,
bbb: BBB
},
actions: {....}
})
----------------------------
在任何 component 內
import { mapActions, mapGetters } from 'vuex
computed: {
...mapGetters({
aaagetter: 'aaa/aaagetter'
}),
...mapState({
aaastate: state => state.aaa.aaastate,
aaastate: function(state) {
return state.aaa.aaastate
}
})
}
methods: {
...mapActions('aaa', ['aaaactions1', 'aaaactions2'])
}
可在 component 內用 this.aaaactions1() 操作
```
https://segmentfault.com/a/1190000022073199
https://dotblogs.com.tw/wasichris/2018/09/06/001935
## Vue Router
https://blog.hinablue.me/2019-ithome-ironman-day-9/
https://medium.com/@linwei5316/vue-router-4c2aad1cc352