浏览代码

Vuex.store 적용 > async fetch + store.dispatch

yongun 5 年之前
父节点
当前提交
bfda3e23bd
共有 2 个文件被更改,包括 36 次插入3 次删除
  1. 11 3
      pages/index.vue
  2. 25 0
      store/index.js

+ 11 - 3
pages/index.vue

@@ -68,9 +68,17 @@
 
 <script>
 export default {
-  async asyncData ({ app }) {
-    const topHeadlines = await app.$axios.$get('/api/top-headlines?country=us')
-    return { headlines: topHeadlines.articles }
+  // async asyncData ({ app }) {
+  //   const topHeadlines = await app.$axios.$get('/api/top-headlines?country=us')
+  //   return { headlines: topHeadlines.articles }
+  // }
+  async fetch ({ store }) {
+    await store.dispatch('loadHeadLines', '/api/top-headlines?country=us')
+  },
+  computed: {
+    headlines () {
+      return this.$store.getters.headlines
+    }
   }
 }
 </script>

+ 25 - 0
store/index.js

@@ -0,0 +1,25 @@
+import Vuex from 'vuex'
+
+const createStore = () => {
+  return new Vuex.Store({
+    state: {
+      headlines: []
+    },
+    mutations: {
+      setHeadLines (state, headlines) {
+        state.headlines = headlines
+      }
+    },
+    actions: {
+      async loadHeadLines ({ commit }, apiUrl) {
+        const { articles } = await this.$axios.$get(apiUrl)
+        commit('setHeadLines', articles)
+      }
+    },
+    getters: {
+      headlines: state => state.headlines
+    }
+  })
+}
+
+export default createStore