【问题标题】:Math.random().toString.slice is not a function in JavascriptMath.random().toString.slice 不是 Javascript 中的函数
【发布时间】:2018-06-03 00:30:29
【问题描述】:

我正在尝试在 Vue JS 2 上设置自定义指令。但我收到了以下错误消息:

TypeError: Math.random(...).toString.slice is not a function

这是我在 main.js 上全局编写的指令:

Vue.directive('rainbow', {
  bind (el, binding, vnode) {
    el.style.color = '#' + Math.random().toString.slice(2, 8)
  }
})

这是我调用指令的地方

<h2 v-rainbow>Hello</h2>

我在网上到处搜索,但信息。 任何帮助或建议都非常受欢迎。谢谢

【问题讨论】:

    标签: javascript vuejs2 vue-directives


    【解决方案1】:

    toString是一个函数,所以你必须按如下方式使用它:

    Math.random().toString().slice(2, 8)
    ----------------------^^^---------
    

    【讨论】:

    • 天哪!我怎么没看到这个!我很惭愧,但非常感谢。 5*
    【解决方案2】:

    如果您尝试生成随机颜色,那么这是正确的方法:

    var colorNumber = Math.floor(Math.random() * 0xffffff); 
    // converting to hexadecimal 
    var colorNumberStr = colorNumber.toString(16);  
    // added 0-s to have fixed 6-length string
    var colorNumberStrPadded = ('00000' + colorNumberStr).slice(-6) 
    el.style.color = '#' + colorNumberStrPadded;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-12
      • 2023-04-11
      • 2018-11-06
      • 1970-01-01
      • 2011-07-31
      • 1970-01-01
      • 2019-06-23
      相关资源
      最近更新 更多