【问题标题】:Binding class with VueJS and Props [duplicate]使用 VueJS 和 Props 绑定类 [重复]
【发布时间】:2018-08-06 10:00:28
【问题描述】:

我有一个名为Avatar.vue的Vue组件,用于创建由用户传递的props定义的头像img,参数imgType定义用户是否要使用带半径边框的img,这是代码

<template>
<div>
    <img
            :class="{'img-circle': isCircle()}"
            src="./assets/defaultImg"
            :height="imgHeight"
            :width="imgWidth"
    >
</div>
</template>

<script>
    export default {
    props: ['imgHeight', 'imgWidth', 'imgType'],
    methods: {
        isCircle: function () {
            return this.imgType.toString() === 'circle';
        }
    }
}
</script>

<style scoped>
.img-circle {
    border-radius: 50%;
}
</style>

这是 HTML 调用者

<div>
     <avatar-img
      :imgHeight="100"
      :imgWidth="100"
      :imgType="circle">
     </avatar-img>
</div>

但是当我调用这个组件时,参数imgType 这会返回一个错误Cannot read property 'toString' of undefined"m sorry if im 解释的不是很好,但我尽力了

【问题讨论】:

  • 你为什么要在String 上打电话给toString()imgType不会成为String 吗?此外,imgType 是否曾经异步填充?
  • 如果我删除toString() type of this.imgType 返回undefined
  • 它试图使用circle 作为变量。将circle 放在单引号中::imgType=" 'circle' " 或删除冒号:imgType="circle"
  • 页面加载时会填充imgType
  • 感谢@zero298 为我工作,没有冒号,你能回答要关闭的帖子

标签: javascript vue.js


【解决方案1】:

您的绑定试图将circle 解释为变量。删除冒号(因为不需要绑定):

<div>
     <avatar-img
      :imgHeight="100"
      :imgWidth="100"
      imgType="circle">
     </avatar-img>
</div>

或将circle 放在单引号中,以便将其解释为字符串(为强调而添加空格):

<div>
     <avatar-img
      :imgHeight="100"
      :imgWidth="100"
      :imgType=" 'circle' "> 
     </avatar-img>
</div>

考虑以下几点:

const app = new Vue({
  el: "#app",
  components: {
    "avatar-img": {
      props: ['imgHeight', 'imgWidth', 'imgType'],
      methods: {
        isCircle: function() {
          return this.imgType === 'circle';
        }
      }
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.js"></script>


<div id="app">
  <avatar-img :img-height="100" :img-width="100" img-type="circle" inline-template>
    <div>
      <img :class="{'img-circle': isCircle()}" src="./assets/defaultImg" :height="imgHeight" :width="imgWidth">
    </div>
  </avatar-img>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-09
    • 2020-10-21
    • 2020-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多