【问题标题】:Can I pass props to a child component and use the data in the parent component in Vue我可以将道具传递给子组件并在Vue中使用父组件中的数据吗
【发布时间】:2020-01-01 22:08:22
【问题描述】:

我想将数据传递给子组件并在父组件中呈现相同的数据。此外,我想在函数中使用数据,而不是简单地将其呈现在子进程中。当我在这个例子中传递道具时,它不再呈现

带有数据的标签

 <template>
  <div class="hello">
    <div v-for="(section, index) in sections" :key="index">
      <p>{{section.name}}</p>
      <p>{{section.type}}</p>
    </div>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      sections: [
        {
          name: "scoop",
          type: "boulder"
        },
        {
          name: "pew pew",
          type: "roped"
        }
      ]
    };
  },
  props: ["sections"]
};
</script>

【问题讨论】:

    标签: vue.js vue-component vue-props


    【解决方案1】:

    您不能对数据和道具使用相同的词/属性名称(在您的情况下为部分)。

    【讨论】:

      【解决方案2】:

      我假设你的代码是父组件:

      // parent.vue
      <template>
        <div class="hello">
          <div v-for="(section, index) in sections" :key="index">
            <p>{{section.name}}</p>
            <p>{{section.type}}</p>
          </div>
          <my-child-component :sections="sections" />
        </div>
      </template>
      
      <script>
      import MyChildComponent from '~/components/MyChildComponent.vue'
      
      export default {
        name: "HelloWorld",
        components: {
          MyChildComponent
        },
        data() {
          return {
            sections: [
              {
                name: "scoop",
                type: "boulder"
              },
              {
                name: "pew pew",
                type: "roped"
              }
            ]
          }
        },
        methods: {
          consoleSections() {
            console.log(this.sections) // the way to use data in function
          }
        }
      }
      </script>
      
      // MyChildComponent.vue
      <template>
        <div class="hello">
          <div v-for="(section, index) in sections" :key="index">
            <p>{{section.name}}</p>
            <p>{{section.type}}</p>
          </div>
        </div>
      </template>
      
      <script>
      
      export default {
        name: "ChildHelloWorld",
        props: ['sections'],
        methods: {
          consoleSections() {
            console.log(this.sections) // the way to use data in child
          }
        }
      }
      </script>
      

      查看关于组件的 vue 指南:https://vuejs.org/v2/guide/components.html

      【讨论】:

        猜你喜欢
        • 2019-11-12
        • 2018-08-11
        • 1970-01-01
        • 1970-01-01
        • 2018-10-10
        • 1970-01-01
        • 2019-03-04
        • 2020-09-01
        相关资源
        最近更新 更多