在 Vue JS 中,从 vue 实例中的方法调用过滤器,但 $options 未定义
In Vue JS, call a filter from a method inside the vue instance but $options is undefined
我已经看到符合我问题的答案:In Vue JS, call a filter from a method inside the vue instance
现在,当做
console.log(this.$options)
我得到 undefined
所以我不能在上面调用 filters
..
这是我的代码:
methods:{
style:(input)=>{
return {
backgroundColor:this.$options.filters.color(input),
}
}
},
filters: {
color: function (value) {
console.log(color(value));
if (!value) return ''
return `rgb(${value},${value},${value})`
}
}
Error in render: "TypeError: Cannot read property 'filters' of undefined"
您正在为样式方法使用箭头函数。应该是:
style(input) {
return {
backgroundColor:this.$options.filters.color(input),
}
}
如果您没有在过滤器中使用 this
,那么您可以将其提取到外部,例如:
function color (value) {
console.log(color(value));
if (!value) return ''
return `rgb(${value},${value},${value})`
}
methods: {
style(input) {
return {
backgroundColor: color(input),
}
}
},
filters: { color }
你可以在methods中写这个函数
methods:{
style:(input)=>{
return {
backgroundColor:this.color(input),
}
},
color: (value) {
console.log(color(value));
if (!value) return ''
return `rgb(${value},${value},${value})`
}
}
我已经看到符合我问题的答案:In Vue JS, call a filter from a method inside the vue instance
现在,当做
console.log(this.$options)
我得到 undefined
所以我不能在上面调用 filters
..
这是我的代码:
methods:{
style:(input)=>{
return {
backgroundColor:this.$options.filters.color(input),
}
}
},
filters: {
color: function (value) {
console.log(color(value));
if (!value) return ''
return `rgb(${value},${value},${value})`
}
}
Error in render: "TypeError: Cannot read property 'filters' of undefined"
您正在为样式方法使用箭头函数。应该是:
style(input) {
return {
backgroundColor:this.$options.filters.color(input),
}
}
如果您没有在过滤器中使用 this
,那么您可以将其提取到外部,例如:
function color (value) {
console.log(color(value));
if (!value) return ''
return `rgb(${value},${value},${value})`
}
methods: {
style(input) {
return {
backgroundColor: color(input),
}
}
},
filters: { color }
你可以在methods中写这个函数
methods:{
style:(input)=>{
return {
backgroundColor:this.color(input),
}
},
color: (value) {
console.log(color(value));
if (!value) return ''
return `rgb(${value},${value},${value})`
}
}