LoginSignup
15
8

More than 3 years have passed since last update.

【Vue.js】怖がらないで、引数分割束縛(argument destructuring)

Last updated at Posted at 2020-09-12

関数({ $axios })とか初見だと、ビビる引数の書き方でてきますよね

その名も引数分割束縛。なんか、恐い言葉です。

これの目的は、何回も記されるコードを因数分解して、省略しちゃおうというのが目的です。

asyncData

contextを省略するパターン

async asyncData(context) {
  const posts = await context.$axios.$get('/posts')
  return { posts }
},

async asyncData({ $axios }) {
  const posts = await $axios.$get('/posts')
  return { posts }
},

contenxtとresを省略するパターン

async asyncData (context) {
  const res = await axios.get('/posts/' + context.params.id)
  return { post: res.data }
}

async asyncData ({ params }) {
  const { data } = await axios.get('/posts/' + params.id)
  return { post: data }
}

Vuexのstore

export const actions = {
  async login (context) {
    await context.commit('switchLogin')
  })
}

export const actions = {
  async login ({ commit }) {
    await commit('switchLogin')
  })
}

つまり、何が起きているか。

まず分割代入の仕組みで、代入

{ a } = { a: 1 }
console.log(a)  // 1

オブジェクトのキーから、代入

let option = { a: 1 }
{ a } = option.a
console.log(a)  // 1

要はこんなことが起きている

export const actions = {
  async login (context) {
    await 〇〇('switchLogin')
  })
}

export const actions = {
  async login ({ commit }) {
    await 〇〇('switchLogin')
  })
}

いずれの場合も、「〇〇」と示せるようにすれば良いから

{ commit } = { commit: 〇〇 }
console.log(commit)  // 〇〇

let context = { commit: 〇〇 }
{ commit } = context.commit
console.log(commit)  // 〇〇
15
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
8