【问题标题】:vue.js making a data property = to the return value of a methodvue.js 将数据属性设置为方法的返回值
【发布时间】:2023-03-10 22:05:01
【问题描述】:

所以我试图分配 this.clean = this.cleaner。

结果道具是我要过滤的 20 个对象的数组。我想要一个对象数组,它们只有一个有效的 poster_path 值,并删除那些不符合该要求的对象。因此 .filter()。

  props: ['results'],
  data() {
    return {
      clean: []
    }
  },
  mounted() {
    this.clean = this.cleaner
  },
  methods: {
    cleaner() {
      return this.results.filter(o => o.poster_path !== null)
    }
  }

问题是使用我的 vue devtool Vue 似乎没有保存 this.cleaner 值。 对于 this.clean 的值,我得到了 {"_custom":{"type":"function","display":"<span>ƒ</span> bound cleaner()"}}

如果我尝试使用计算值,我会不断收到“(评估期间的错误)”作为 this.clean 的值。

如果我尝试this.clean = this.cleaner(),它只会保存一个空数组。

【问题讨论】:

    标签: javascript vue.js computed-properties


    【解决方案1】:

    只需像这样分配函数的功能

    props: ['results'],
    data() {
      return {
       clean: []
      }
    },
    mounted() {
      this.clean = this.results.filter(o => o.poster_path !== null)
    }    
    

    【讨论】:

    • 仍然让我认为 this.clean 是一个空数组。甚至尝试使过滤器有条件地确定为真,但仍然是一个空数组
    【解决方案2】:

    试试这个 sn-p。我认为您的代码可以简化为:

    const mockData = [
      {
        name: 'abc',
        poster_path: 1
      },
      {
        name: 'def',
        poster_path: null
      }
    ]
    Vue.component('foo', {
      props: ['results'],
      template: '<ul><li v-for="c in clean" :key="index">{{c.name}}</li></ul>',
      computed: {
        clean: function() {
          return this.results ?this.results.filter(o => o.poster_path !== null) : [];
        }
      }
    })
    var app = new Vue({
      el: '#app',
      data() {
        return { results: mockData }
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app">
      Foo component: <foo :results="results"/>
    </div>

    【讨论】:

    • 这个过滤后的数据将用于子组件的 v-for 中。我需要过滤道具,然后将结果分配为数据变量,以便我可以“v-for in”
    • @CiaranO'Riordan 查看示例
    • @CiaranO'Riordan 顺便说一句,欢迎来到 SO。如果您有机会,请告诉我这是否回答了您的问题,如果可以,请将答案标记为已接受。
    • 谢谢亚历克斯!你的方式肯定更干净。认为我已将问题缩小到过滤器。使用您的代码示例我得到一个类型错误:o 为空。我在结果道具中的数据与您的模拟数据完全一样,所以我不知道它为什么会出错。感谢您的帮助!
    • @CiaranO'Riordan 你试过运行新代码 sn-p 吗?
    【解决方案3】:
    props: ['results'],
    data() {
      return {
        clean: this.results.filter(o => o.poster_path !== null)
      }
    },
    

    请试一试。 可以直接将 props 导入到组件数据中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-03
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      • 2020-08-22
      • 1970-01-01
      • 2019-02-04
      • 1970-01-01
      相关资源
      最近更新 更多