7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Nuxt + TypeScript で 2つ以上の値をコンポーネントに渡して変更を受け取る方法

Last updated at Posted at 2019-07-29

nuxt-property-decorator (vue-property-decorator) を使用しているとき、
親コンポーネントから、子コンポーネントに2つ以上の値を渡し、その変更を受け取る方法。

意外と解決するのに手間取ったので、備忘録として。

Nuxt (Vue) + TypeScript

  • 親コンポーネント
Parent.vue
<template>
  <div>
    <p>Value A: {{ valueA }}</p>
    <p>Value B: {{ valueB }}</p>
    <Child
      :value-a.sync="valueA"
      :value-b.sync="valueB"
    />
  </div>
</template>
<script lang="ts">
import { Vue, Component } from 'nuxt-property-decorator'
import Child from '~/components/Child.vue'

@Component({
  components: {
    Child,
  },
})
export default class Parent extends Vue {
  valueA: string = ''

  valueB: string = ''
}
</script>
  • 子コンポーネント
Child.vue
<template>
  <div>
    <input v-model="computedValueA"> -
    <input v-model="computedValueB">
  </div>
</template>
<script lang="ts">
import { Vue, Component, Prop } from 'nuxt-property-decorator'

@Component
export default class Parent extends Vue {
  @Prop({ required: true })
  valueA: string

  @Prop({ required: true })
  valueB: string

  get computedValueA() {
    return this.valueA
  }

  set computedValueA(value) {
    this.$emit('update:valueA', value)
  }

  get computedValueB() {
    return this.valueB
  }

  set computedValueB(value) {
    this.$emit('update:valueB', value)
  }
}
</script>

対応するJavaScriptでの書き方(Child.vue)

export default {
  props: {
    valueA: {
      type: String,
      required: true,
    },
    valueB: {
      type: String,
      required: true,
    },
  },
  computed: {
    computedValueA: {
      get() {
        return this.valueA
      },
      set(value) {
        this.$emit('update:valueA', value)
      },
    },
    computedValueB: {
      get() {
        return this.valueB
      },
      set(value) {
        this.$emit('update:valueB', value)
      },
    },
  },
}

構成

package.json
  "dependencies": {
    ...
    "@nuxt/config": "^2.8.1",
    "@nuxt/typescript": "^2.8.1",
    "nuxt": "^2.8.1",
    "nuxt-property-decorator": "^2.3.0",
    "ts-node": "^8.2.0"
  },
  "devDependencies": {
    ...
    "@babel/runtime-corejs3": "^7.4.5",
    "@types/node": "^12.0.7",
    "@types/webpack-env": "^1.13.9",
    "babel-core": "7.0.0-bridge.0",
    "babel-preset-vue": "^2.0.2",
    "webpack-merge": "^4.2.1",
  }

Nuxt関係ないね。Vueだね。

7
4
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
7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?