【问题标题】:How to change props of another component in parent component如何更改父组件中另一个组件的道具
【发布时间】:2019-11-14 05:00:25
【问题描述】:

我创建了一个小部件(如果您愿意,可以是子组件),它显示我已经推送到 NPM 以在另一个(如果您愿意的话是父组件)组件中使用的图像,这是一个全新的项目。鉴于我使用 NPM 的情况,如何从父组件更改此子组件的 props 值?我想将显示的图像数量从 5 更改为 10。

子组件显然在父组件中工作,我已经尝试更改我定义组件的下方的 prop 值。

父组件(“Widget”是子组件,是一个任意名称,在我尝试更改道具之前一直在工作):

<template>
  <Widget></Widget>
</template>

<script>
import Widget from "widget";
export default {
  name: "app",
  components: {
    Widget: {
      props: {
        perPage: {
          type: Number,
          default: 10
        }
      }
    }
  }
};
</script>

在 NPM 上发布的子组件:

<script>
export default {
  name: 'Widget',
  props: {
    perPage: {
      type: Number,
      default: 5
    }
  }
}
</script>

我想将“perPage”“默认值”从 5 更改为 10,如上面的代码所示。提供的代码应该足以解决这个问题,但如果需要更多代码,我也可以提供。谢谢!

只想重申 NPM 的子组件在父组件(这是一个全新的项目)中处于正常工作状态,直到我尝试更改 prop 值。

【问题讨论】:

  • 我看不到你如何将道具从父母传递给孩子,因为我可以看到它只能使用默认值,因为没有值从父母传递给孩子
  • 你能详细说明一下吗?抱歉,我是 vue 新手
  • 当然,我会编辑我的答案
  • @Plastic 刚刚意识到你的答案正是我的代码哈哈。话虽如此,它仍然不起作用 - 该应用程序实际上给了我一个空白屏幕。您是否认为因为这使用了 NPM 和另一个项目/应用程序,所以它不像 vue.js 文档中所述的那样工作?
  • 这个链接几乎解决了它...alligator.io/vuejs/intro-to-component-props

标签: javascript jquery vue.js vue-component


【解决方案1】:

我会通过小部件模板传递道具

你可以读到vue.js docs,如果你想通过模板最好的方式从父级到子级动态传递一些信息,所以在你的应用模板中你将通过小部件标签传递数据

<template>
  <Widget :perPage ="perPage"></Widget>
</template>

<script>
import Widget from './Widget.vue'; //assuming they are in the same folder

export default {
  components: {
     Widget
  },
  data() {
     return {
        perPage: 5
     }
  }
}
</script>

//Widget.vue
<template>
  <p>Per Page: {{perPage}}</p>
</template>

<script>
export default {
    name: 'Widget',
    props: [
      'perPage'
    ]
 }
</script>

【讨论】:

  • 如果可能的话,我希望子组件中的道具保持在 5
猜你喜欢
  • 2021-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-11
  • 1970-01-01
  • 2018-08-06
  • 2020-10-18
相关资源
最近更新 更多