Reputation: 183
I'm trying to set up a custom directive on Vue JS 2. But I got this error message:
TypeError: Math.random(...).toString.slice is not a function
Here is my directive written globally on main.js:
Vue.directive('rainbow', {
bind (el, binding, vnode) {
el.style.color = '#' + Math.random().toString.slice(2, 8)
}
})
Here is where I'm calling my directive
<h2 v-rainbow>Hello</h2>
I searched everywhere on the web but info. Any help or suggestions is more than welcome. Thx
Upvotes: 2
Views: 2299
Reputation: 48793
If you are trying to generate random color, then this is the correct way:
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;
Upvotes: 1
Reputation: 48337
toString
is a function, so you have to use it in the following way:
Math.random().toString().slice(2, 8)
----------------------^^^---------
Upvotes: 6