javascript - 在 VueJS 中使用 prop 值作为变量

标签 javascript vue.js vuejs2

我在 VueJS 中使用 prop value 作为变量时遇到问题。我有一个传输 Prop 的组件:

这是父组件:

<template>
  <div class="a">
    <UploadAvatarModal
      apiurl="upload_avatar"
      id="UploadAvatarModal"
    />
  </div>
</template>

这是UploadAvatarModal组件的脚本:

<template>
  <div class="a">
     ...
  </div>
</template>
<script>
export default {
  props: {
    id: String,
    apiurl: String
  },
  methods: {
    def: function () {
      this.$refs.id.hide()
    }
  }
}
</script>

在这一行中: this.$refs.id.hide() 如何根据 prop id 调用方法。示例: this.$refs.UploadAvatarModal.hide() 或 this.$refs.UploadAvatarModal2.hide() 被 props 值更改?

最佳答案

您可以访问 Prop :

this.propName

要访问 id 属性,您需要执行以下操作:

this.id

所以你写的行 this.$refs.id.hide() 应该写成:

this.$refs[this.id].hide()

但它可能不会做任何事情,因为 .hide() 是一个 jquery 函数。 在纯 JavaScript 中,您需要执行以下操作:

this.$refs[this.id].style.display = 'none'

也就是说,这样做可能不是一个好主意。 使用 vue,显示/隐藏组件的最佳方法可能是使用 v-ifv-show

关于javascript - 在 VueJS 中使用 prop 值作为变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48090825/

相关文章:

vue.js - Vite如何使用sass

javascript - Vue 与 bootstrap-vue : prevent more than one expanded list-element at all times in list (v-for)

javascript - 如何使 jQuery 动画仅显示在 div 容器/横幅中

javascript - 空白 PNG/受污染的 Canvas 可能无法导出(不使用图像)

typescript - 在从组合 API 创建的生命周期钩子(Hook)中使用它

javascript - 如何使用 v-for 删除行

javascript - 通过 jQuery 将 H3 标签变成链接?

javascript - 使用 jQuery 遍历列表项

javascript - webpack-dev-server npm run dev 抛出 TypeError : Cannot set property 'port' of undefined

javascript - 如何同时搜索 vendor 名称?