vue.js - Nuxt 在 hook fetch/asyncData 中访问组件的方法或数据
问题描述
在我的组件上,我有以下脚本:
<script>
export default {
data(){
return {
posts: [],
}
}
methods: {
async get_post(){
return await this.$axios('post')
}
}
}
</script>
我想在不直接使用 axios 的情况下从 fetch 或 asyncData 挂钩访问我的数据和方法,在 fetch 上尝试了“this”,但只能访问数据而不是方法,在 asyncData 上我什至无法访问这两者。
解决方案
根据文档:数据获取
asyncData
您只能访问上下文asyncData()
(另外,请记住asyncData()
仅在页面组件中可用)
所以你可以像这样编码
<script>
export default {
asyncData({ $axios }){
return $axios.post('/users')
}
}
</script>
fetch
但您可以访问其中的数据和方法fetch()
export default {
data: () => ({
posts: []
}),
async fetch() {
this.posts = await this.$http.$get('https://api.nuxtjs.dev/posts')
},
fetchOnServer: false,
// multiple components can return the same `fetchKey` and Nuxt will track them both separately
fetchKey: 'site-sidebar',
// alternatively, for more control, a function can be passed with access to the component instance
// It will be called in `created` and must not depend on fetched data
fetchKey(getCounter) {
// getCounter is a method that can be called to get the next number in a sequence
// as part of generating a unique fetchKey.
return this.someOtherData + getCounter('sidebar')
}
}
推荐阅读
- amazon-web-services - 我如何将 AWS RDS 连接到 mysql Kubernetes Pod
- django - ImageField 需要安装 Pillow
- python - Python - 将数据插入数据库时,索引 62 处不支持的格式字符“,”(0x2c)
- ruby-on-rails - 在 Rails 6 中使用 webpack 使 jQuery UI 全局函数可用
- amazon-cognito - 使用 openid 将 blazor 与 aws cognito 集成
- java - Spring Boot JSON 序列化与父表
- sql - 定义一个变量作为查询的结果
- linux - ESXI:从虚拟机本身获取机器名称?
- java - 如何迁移房间数据库?
- c# - 如何使用单例类在 2 个视图模型之间发送 EventAggregator