无法在组件之间传递数据

时间:2016-11-30 17:31:54

标签: vue.js

如何将组件中的方法创建的对象数组传递给另一个组件?我尝试过使用道具,但也许我对道具运作方式的理解是不正确的。

<template>
    <div class="media-body">

    <ul>
        <li v-for="item in items" v-bind:class="{ active: item.active }">{{ item.text }} 
        </li>
    </ul>

      <button type="button" class="btn btn-danger" v-on:click="addItem">Test</button>

</template>

<script>


export default {

    data() {
        return {
            item: "a",
            item2: "b",
            item3: "c",
            item4: "d",
            items: [],
    }
        },  

    methods: {

        addItem: function () {

            var testArray = this.item.concat(this.item2, this.item3, this.item4);

            for (var i = 0; i < testArray.length; i++) {
                this.items.push({
                    text: testArray[i],
                    active: false   });
            }

            // if I check console.log(this.items) at this point I can see the data I want to pass
        },

    }
}

</script>

辅助组件I尝试将数据传递给。

<template>
    <div class="media-body">
      <div class="media-label">Title:
        <textarea class="form-control" placeholder="Title"></textarea>
        </div> 
      </div>
</template>

<script>

export default {

props: ['items'], 

data() {
    return {

    }
},  

</script>

1 个答案:

答案 0 :(得分:1)

要将道具传递给其他组件,您必须在第一个组件中编写以下代码:

  1. 在HTML代码中添加了<secondComponent :items="items" />
  2. 在vue组件中导入并使用secondComponent,如下所示:components: [secondComponent]
  3. 以下是包含这些更改的完整代码:

    <template>
         <div class="media-body">
         <ul>
            <li v-for="item in items" v-bind:class="{ active: item.active }">{{ item.text }} 
            </li>
         </ul>
          <button type="button" class="btn btn-danger" v-on:click="addItem">Test</button>
         <secondComponent :items="items" />
      </template>
    
    <script>
      import secondComponent from '/path/of/secondComponent'
       export default {
        components: [secondComponent]
        data() {
            return {
                item: "a",
                item2: "b",
                item3: "c",
                item4: "d",
                items: [],
        }
            },  
    
        methods: {
    
            addItem: function () {
    
                var testArray = this.item.concat(this.item2, this.item3, this.item4);
    
                for (var i = 0; i < testArray.length; i++) {
                    this.items.push({
                        text: testArray[i],
                        active: false   });
                }
    
                // if I check console.log(this.items) at this point I can see the data I want to pass
            },
    
        }
    }
    
    </script>
    

    在第二个组件中,您已经将项目定义为道具,您也可以在第二个组件的模板/ HTML中使用。

相关问题