vue.js - 如何正确调用 NuxtServerInit?
问题描述
当我尝试在 Vuex 商店上使用 nuxtServerInit 调用 rest api 时,它不会调用,但如果在组件或页面上调用 rest api,它就可以工作。
存储/index.js
import axios from 'axios'
export const state = () => ({
news: [],
})
export const mutations = {
SET_NEWS(state, posts) {
state.news = posts
}
}
export const actions = {
async nuxtServerInit({ commit }, ctx) {
const res = await axios.get('https://api/news.json')
commit('SET_NEWS', res.data)
},
}
export const getters = {
getNews(state) {
return state.news
}
}
页面/新闻/index.vue
computed: {
getNews() {
return this.$store.getters.getNews
}
}
解决方案
尝试在您的 vuex 操作中像这样调用您的 API:
export const actions = {
async nuxtServerInit({ commit }, { req }) {
const res = (await this.$axios.$get('https://api/news.json')).data
commit('SET_NEWS', res)
},
}
推荐阅读
- c# - 在 Visual Studio 中运行应用程序时如何运行单元测试
- sql - 结合两个 sql 查询,每个查询都有一个 with 子句
- ionic3 - ionic 3 textarea 自动调整大小(不是 ion-textarea)
- sql - like 语句是否会吸引 SQL 注入
- c# - Mongodb使用.net core 2.2连接错误
- css - 如何消除孩子之间的垂直差距
- activemq - 一个 MQTT 订阅者可以同时接收同一主题的多条消息吗?
- ruby-on-rails - Ruby On Rails 设计:如何在注册期间避免电子邮件唯一性验证并重写以检查它是否只有在角色“X”时才唯一
- url-rewriting - 网址重写规则不重定向
- bash - 如何按列号过滤这些数据?