nuxtendという気持ち悪いNuxt.jsのライブラリを作っていますが、先ほどもっと気持ち悪くなったので紹介します。
nuxtendにはもともと下記の機能があります。
- mixinにasyncData()/fetch()を書いても反映されない問題を解決
- asyncData()/fetch() でthisを通してmapActions()したアクションを呼べない問題を解決
そして新たに下記のような(気持ち悪い)書き方が可能になりました。
Nuxtに慣れている人ほど気持ち悪く感じると思います。
export default nuxnted({
nuxtend: {
actions: ['apple'] // メソッドを生成するための定義
},
async asyncData () {
// 'apples/get' アクションが存在すれば呼びます。なければ、$axios.get('/apples/10') を呼びます
const res = await this.getApple(10)
// 同様に下記のように呼び出しできます
// action: 'apples/getList' api: $axios.get('/apples', {params: {status: 'dropped'}})
this.getAppleList({status: 'dropped'})
// action: 'apples/create' api: $axios.post('/apples', {status: 'dropped'})
await this.postApple({status: 'dropped'})
// action: 'apples/update' api: $axios.put('/apples/10', {status: 'dropped'})
await this.putApple({id: 10, params: {status: 'dropped'}})
// action: 'apples/delete' api: $axios.delete('/apples/10')
await this.deleteApple(10)
return {
apple: res.data
}
}
})
裏では禍々しいことをしていますが、pagesのコードが綺麗な感じに書けます。