【发布时间】:2021-03-31 21:40:07
【问题描述】:
我正在创建一个简单的 Vuejs div 组件(以显示特定值),它需要接收:lists、placeholder 和 value 作为道具。我正在尝试用我的数据库中的数据显示值,如果用户从lists 中选择一个新值,它应该采用该新值并显示它。但是,如果用户从不选择新值并且数据库中的数据为空,则应显示placeholder。
所以我使用filters 来实现这一点。但是,它输出一个错误:"Cannot read property 'lists' of undefined",它来自filters(我知道,因为如果我注释掉filters,它不会输出错误)。当我将filter 更改为:
filters: {
placeholderFilter () {
return this.placeholderText || this.placeholder
}
}
上面写着:“"Cannot read property 'placeholderText' of undefined"”。所以我想知道过滤器属性是否在data 和props 属性之前执行。它们的执行顺序是什么?我在下面附上了一些相关的代码。无论如何,如果你能想出一个更好的方法来实现这一点。我会很感激的!
这是我的组件:
<template>
<div>{{ placeholderText | placeholderFilter }}</div>
<li @click="pickItem(index)" v-for="(list,index) in lists" :key="index">{{ list }}</li>
</template>
<script>
export default {
props: {
lists: {
type: Array,
required: true
},
value: {
type: [String, Number],
default: ''
},
placeholder: {
type: String,
default: ''
}
},
data () {
return {
selected: -1,
placeholderText: this.value || this.placeholder
}
},
methods: {
pickItem (index) {
this.selected = index
}
},
filters: {
placeholderFilter () {
return this.lists[this.selected] || this.placeholderText || this.placeholder
}
}
}
</script>
这就是我使用它的地方:
<my-component
placeholder="Please type something"
value="Data from database"
lists="['option1','option2','option3']"
>
</my-component>
【问题讨论】:
-
在这种情况下,我只会使用计算属性。过滤器实际上是用于转换文本。这个占位符文本对我来说是一个明显的计算属性。尝试使用计算属性而不是过滤器。
-
谢谢。我已经考虑过了。我会尝试回到计算属性
-
无论如何,我仍在尝试了解 Vuejs 的幕后情况。这对我来说没有意义,应该首先根据我的理解执行
props属性,在去filters之前应该定义lists -
如下所述,只是一个简单的方法。记住过滤器是可重复使用的。如果它们绑定到实例数据,它们就不能重用。所以不能这样用。
标签: javascript vue.js vuejs2