nic*_*vic 6 fetch server-side-rendering vuex nuxt.js
我有一个使用 nuxt Universe SSR 的项目。我使用 fetch 方法获取布局上的数据,并触发存储操作调度。但这根本不起作用...
这是代码。这是默认布局文件:
import Navbar from '~/components/Navbar'
export default {
components: {
Navbar
},
async fetch ({ store }) {
await store.dispatch('fetchItems')
}
}
Run Code Online (Sandbox Code Playgroud)
这是 vuex 商店:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = () => new Vuex.Store({
state: {
allItems: [],
currentCategories: []
},
mutations: {
setItems (state, allItems) {
state.allItems = allItems
},
setCurrentCategories (state, currentCategories) {
state.currentCategories = currentCategories
}
},
actions: {
async fetchItems ({ commit, dispatch }) {
try {
const { data: { items } } = await this.$axios.get('/api/catalog/categories?limit=0')
commit('setItems', items)
dispatch('getCurrentCategories')
} catch (e) {
console.error(e)
}
},
getCurrentCategories ({ commit }, payload) {
const newCategories = []
if (!payload) {
this.state.allItems.forEach((item) => {
if (!item.parent_id) {
newCategories.push(item)
}
})
} else {
this.state.allItems.forEach((item) => {
if (item.parent_id === payload) {
newCategories.push(item)
}
})
}
commit('setCurrentCategories', newCategories)
}
},
getters: {
allItems: s => s.allItems,
currentCategories: s => s.currentCategories
}
})
export default store
Run Code Online (Sandbox Code Playgroud)
看起来 fetch 方法根本没有触发。我尝试在 fetch 方法内的 console.log 中放入一些内容,但我在控制台中看不到输出...我是 nuxt 的新手,我以前使用过 vue。任何建议都将受到高度赞赏。
小智 6
改为这样做:
async fetch () {
await this.$store.dispatch('fetchItems')
}
Run Code Online (Sandbox Code Playgroud)
小智 1
如果该功能没有被触发,可能是其路径不正确。Nuxt 建议将 Vuex 与模块一起使用:https://nuxtjs.org/docs/2.x/directory-struction/store
每个模块都是namespaced.
items.js因此,对于您的情况,我将在商店目录中创建一个文件。并且,在布局文件中,我将触发如下函数:
store.dispatch('items/fetchItems');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8029 次 |
| 最近记录: |