【问题标题】:VueJS - How do I use props in same component to specify the value in another componentVueJS - 如何在同一个组件中使用道具来指定另一个组件中的值
【发布时间】:2021-01-06 11:58:09
【问题描述】:

我是 vuejs 的新手,我想知道如何将 props 用于挂载另一个组件的功能。下面我将展示我是如何尝试的。

这是我的 Component.vue

<template>
  <div class="Passing prop value">
    <chart :id="'3'"></chart>
  </div>
  <div class="Passing prop value second time">
    <chart :id="'8'"></chart>
  </div>
</template>

<script>
import chart from '.chartline.vue'
export default{
    props: {
        id: {
            type: String,
            required: true 
         }
    },
  components: {chart},
  mounted (){
    this.$http.get('api/goes/here' + this.id ) <-- here id should get value 3 for 1st div and value 8 for second div
  }
}
</script>

我在组件中传递了 id 值,并且我希望在挂载的函数中具有相同的值。

你可以尝试通过使用道具来实现它,但不知道浏览器中没有显示任何内容,所以这是使用道具的正确方法。

目标:我想在导入的组件中给出 id 并在那里指定值。请帮帮我。

【问题讨论】:

  • 使用 this.id 定义 props
  • 首先,它应该是this.id 你试图在同一个组件中检索?
  • 我也应该在组件 b 中定义 props 吗?
  • 不,我正在使用上面提到的两个不同的组件,我只是想知道如何在道具中传递值并在挂载函数中使用该道具
  • 您可能应该获取所有 id,然后循环遍历它们以显示值 38。或者在调用api的chart组件上写一个方法(给方法希望的id作为c的参数)。

标签: vue.js reusability


【解决方案1】:
Firstafall let me add a solution assuming that your prop 'id' contains just one value
```
<template>
  <div class="Passing prop value">
    <chart :id="getId"></chart>
  </div>
</template>

<script>
import chart from '.chartline.vue'
export default{
    props: {
        id: {
            type: String,
            required: true 
         }
    },
  components: {chart},
  computed: {
    getId() {
       return this.id;
    }
  }
  mounted (){
    this.$http.get('api/goes/here' + this.id ) <-- here id should get value 3 for 1st div and value 8 for second div
  }
}
</script>

// Secondly like if your response has a array of id's then you can do this in this way

```
<template>
  <div v-for="idd in getIds" class="Passing prop value">
    <chart :id="idd"></chart>
  </div>
</template>

<script>
import chart from '.chartline.vue'
export default{
    props: {
        id: {
            type: String,
            required: true 
         }
    },
    data() {
      return {
      ids: []
      };
    }
    components: {chart},
    computed: {
      getIds() {
       return this.ids;
      }
    }
    mounted (){
    this.ids = this.$http.get('api/goes/here' + this.id ) <-- Assuming that the 
    response is an array
    }
}
```

【讨论】:

  • 另外请检查我编辑的答案,看看它是否有帮助@Quantum
猜你喜欢
  • 2021-08-15
  • 2017-07-05
  • 2020-07-23
  • 2019-11-14
  • 1970-01-01
  • 2020-05-08
  • 2019-12-05
  • 2019-06-12
  • 1970-01-01
相关资源
最近更新 更多