【问题标题】:Understanding the order of properties execution in Vuejs [duplicate]了解Vuejs中属性执行的顺序[重复]
【发布时间】:2021-03-31 21:40:07
【问题描述】:

我正在创建一个简单的 Vuejs div 组件(以显示特定值),它需要接收:listsplaceholdervalue 作为道具。我正在尝试用我的数据库中的数据显示值,如果用户从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"”。所以我想知道过滤器属性是否在dataprops 属性之前执行。它们的执行顺序是什么?我在下面附上了一些相关的代码。无论如何,如果你能想出一个更好的方法来实现这一点。我会很感激的!

这是我的组件:

<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


【解决方案1】:

过滤器未绑定到组件实例,因此它们根本无法通过this 关键字访问它。它们总是被传递一个参数并返回该参数的转换版本。所以换句话说,它们只是方法。由于这个原因,它们在 Vue 3 中完全被删除了。

是的,你在这里寻找的是一个计算出来的!

【讨论】:

    猜你喜欢
    • 2013-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-02
    • 2014-04-16
    • 1970-01-01
    • 2021-05-02
    相关资源
    最近更新 更多