LoginSignup
11
14

More than 5 years have passed since last update.

Vue.jsの入れ子のComponentで {{ Hoge.fuga }} を渡したいだけの人生だった。

Last updated at Posted at 2016-07-06

前提

  • 非同期通信で親子関係をもったリストをとりたい
  • 今回は DataBase - Table みたいな親子関係でDataBaseのnameをキーにTable一覧をとるAPIを叩く想定
  • 親(Hoge)のプロパティ(fuga)を子供に受け渡すことのみを命をかけている。

結論

これでうまくいきました。死んだ僕達の願いは後半に書いてます。

var parent = Vue.extend({
    name: 'parent-component',
    template:
        '<li v-for="database in databases">' +
            '<child-component v-bind:database="database.name"></child-component>' +
        '</ul>'
    ,
    data: function () {
        return {
            databases: []
        }
    },
    created: function () {
        var that = this;
        axios.get('/database')
            .then(function (response) {
                that.databases = response.databases;
            });
    }
});

var child = Vue.extend({
    name: 'child-component',
    props: ['database'],
    template: 
      '<li v-for="table in tables">' +
          '<a href="#">{{ table.name }}</a>' +
      '</li>',
    data: function () {
        return { tables: [] }
    },
    created: function() {
        var that = this;
        axios.get('/database/' + that.database)
            .then(function (response) {
                that.tables = response.tables;
            });
    }
});

Vue.component('parent-component', parent);
Vue.component('child-component', child);

ハマったところ

子コンポーネントへの値の渡し方

あれやこれや試して上記にたどりついた。
数々の死んだ俺たちを以下に残します。

1. 普通に渡してみた

var parent = Vue.extend({
    name: 'parent-component',
    template:
        '<li v-for="database in databases">' +
            '<child-component database="{{ database.name }}"></child-component>' +
        '</ul>'
    ,
    ...
});

変更点は以下の行

<child-component database="{{ database.name }}"></child-component>

こうすると、childのcreatedで this.database したときに {{ database.name }} ってそのまま出て儚くも私は散りました。

2. 子供から親を取得しようとした

var child = Vue.extend({
    name: 'child-component',
    ...
    created: function() {
        var that = this;
        var databases = that.$parent.databases;
        // で?
    }
});

で?

3. なんかエラー出た系

child側の props 書かないと

[Vue warn]: Attribute "v-bind:XXX" is ignored on component <xxx-xxx> because the component is a fragment instance: http://vuejs.org/guide/components.html#Fragment-Instance

って怒られて最後の僕が死んだ結果、うまいこといきましたとさ。

11
14
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
11
14