state
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <!-- state是數據 Vuex中有一個構造函數是Store 我們想要創建vuex實例就需要new這個store const store = new Vuex.Store({ state: { } }) const app = new Vue({ store }) 將store放入vue的配置對象后,該 store 實例會注入到根組件下的所有子組件中 在獲取state中的值時,在組件中寫computed computed: { 數據名 () { return this.$store.state.數據名 } } --> </body> </html>
getter
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>title</title> </head> <table> </table> <body> <!--
getters中的所有getter都是函數 每個getter中都有一個state參數 每個getter中都有第二個參數getters getter返回的除了數據以外還可以返回函數,這樣可以通過傳參的方式,得到對應的數據 getter直接返回的是數據,那么在使用時 computed: { 數據名 () { return this.$store.getters.getter名 } } 如果返回的是函數 computed: { 數據名 () { return this.$store.getters.getter名(參數) } } --> </body> </html>
mutation <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>title</title> </head> <table> </table> <body> </body> <script> 修改state只能用mutation去進行修改 mutations: { mutation (state) { // 因為mutation要修改state,所以他的第一個參數為state mutation想要被調用,需要在一些地方調用this.$store.commit('mutation') } } // 觸發mutation store.commit('mutation') 大部分情況我們需要給mutation提交數據 store.commit('mutation', 數據) 那么在mutation的第二個參數中就是commit過來的數據 mutations: { mutation (state, payload) { payload就是commit過來的數據 } } </script> </html>
action <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>title</title> </head> <table> </table> <body> /* action中就是專門完成異步請求的 發起請求,請求成功后commit(mutation, 請求結果)將數據發送給mutation */ </body> </html>