是否有可能在Vue.Js中传递计算属性中的参数。我可以看到,当有getter /setter使用computed时,他们可以接受一个参数并将其分配给一个变量。比如这里的文档:

computed: {
  fullName: {
    // getter
    get: function () {
      return this.firstName + ' ' + this.lastName
    },
    // setter
    set: function (newValue) {
      var names = newValue.split(' ')
  
      this.firstName = names[0]
      this.lastName = names[names.length - 1]
    }
  }
}

这也是可能的吗:

computed: {
  fullName: function (salut) {
    return salut + ' ' + this.firstName + ' ' + this.lastName    
  }
}

其中computed属性接受一个参数并返回所需的输出。然而,当我尝试这样做时,我得到这个错误:

vue.common.js:2250 Uncaught TypeError: fullName不是函数(…)

我是否应该在这种情况下使用方法?


当前回答

我没有看到一个清晰的Vue 3的例子,所以我添加了一个我工作的应用程序。首先调用一个方法,然后返回一个计算值。因此,该方法将在Vue重新渲染时被调用,但随后将返回缓存的计算值,并且仅在响应性输入变量发生变化时才执行。

<script setup>
import { computed, ref } from 'vue'

const itemOne = ref(1);
const itemTwo = ref(2);

const getItemDoubled: (key) => {
    return computed(()=> item[key].value * 2);
}
</script>

<template>
    <p>get dynamic name computed value: {{ getItemDoubled('One') }}
    <p>get dynamic name computed value: {{ getItemDoubled('Two') }}
</template

其他回答

我没有看到一个清晰的Vue 3的例子,所以我添加了一个我工作的应用程序。首先调用一个方法,然后返回一个计算值。因此,该方法将在Vue重新渲染时被调用,但随后将返回缓存的计算值,并且仅在响应性输入变量发生变化时才执行。

<script setup>
import { computed, ref } from 'vue'

const itemOne = ref(1);
const itemTwo = ref(2);

const getItemDoubled: (key) => {
    return computed(()=> item[key].value * 2);
}
</script>

<template>
    <p>get dynamic name computed value: {{ getItemDoubled('One') }}
    <p>get dynamic name computed value: {{ getItemDoubled('Two') }}
</template

我想首先重申前面的警告,使用computed(被缓存的)参数只会使computed不被缓存,实际上只是使它成为一个方法。

然而,话虽如此,这里是我能想到的所有可能有边界情况的变化。如果你将其剪切并粘贴到演示应用中,你就会清楚发生了什么:

<template>
  <div>

    <div style="background: violet;"> someData, regularComputed: {{ someData }}, {{ regularComputed }} </div>
    <div style="background: cornflowerblue;"> someComputedWithParameterOneLine: {{ someComputedWithParameterOneLine('hello') }} </div>
    <div style="background: lightgreen;"> someComputedWithParameterMultiLine: {{ someComputedWithParameterMultiLine('Yo') }} </div>
    <div style="background: yellow"> someComputedUsingGetterSetterWithParameterMultiLine: {{ someComputedUsingGetterSetterWithParameterMultiLine('Tadah!') }} </div>

    <div>
      <div style="background: orangered;"> inputData: {{ inputData }} </div>
      <input v-model="inputData" />
      <button @click="someComputedUsingGetterSetterWithParameterMultiLine = inputData">
        Update 'someComputedUsingGetterSetterWithParameterMultiLine' with 'inputData'.
      </button>
    </div>

    <div style="background: red"> newConcatenatedString: {{ newConcatenatedString }} </div>

  </div>
</template>

<script>

  export default {

    data() {
      return {
        someData: 'yo',
        inputData: '',
        newConcatenatedString: ''
      }
    },

    computed: {

      regularComputed(){
        return 'dude.'
      },

      someComputedWithParameterOneLine(){
        return (theParam) => `The following is the Parameter from *One* Line Arrow Function >>> ${theParam}`
      },

      someComputedWithParameterMultiLine(){
        return (theParam) => {
          return `The following is the Parameter from *Multi* Line Arrow Function >>> ${theParam}`
        }
      },

      // NOTICE that Computed with GETTER/SETTER is now an Object, that has 2 methods, get() and set(), so after the name of the computed we use : instead of ()
      // thus we do: "someComputedUsingGetterSetterWithParameterMultiLine: {...}" NOT "someComputedUsingGetterSetterWithParameterMultiLine(){...}"
      someComputedUsingGetterSetterWithParameterMultiLine: {
        get () {
          return (theParam) => {
            return `As part of the computed GETTER/SETTER, the following is inside get() which receives a Parameter (using a multi-line Arrow Function) >>> ${theParam}`
          }
        },
        set(newSetValue) {
          console.log('Accessing get() from within the set()', this.someComputedUsingGetterSetterWithParameterMultiLine('hello from inside the Setter, using the Getter.'))
          console.log('Accessing newSetValue in set() >>>>', JSON.stringify(newSetValue))
          this.newConcatenatedString = `**(1)${this.someComputedUsingGetterSetterWithParameterMultiLine('hello from inside the Setter, using the Getter.')}**  This is a concatenation of get() value that had a Parameter, with newSetValue **(2)${newSetValue}** that came into the set().`
        }
      },

    },

  }

</script>

我没有看到Vue3和/或使用组合API的答案,所以这里是我的位(,因为我总是忘记如何做到这一点)。

你可以通过将computed包装在另一个函数中来让它接受参数,就像这样:

const firstName = ref("John");
const lastName = ref("Doe");

const fullName = (salut: string) =>
  computed(() =>
    `${salut} ${firstName.value} ${lastName.value}`);

如果你想使用Pinia(传递参数给getter)进行状态管理,你可以使用这个计算getter:

// In component's setup function

const store = useStore();
const fullName = store.fullName("Hello"); // ComputedRef<string> 
console.log(fullName) // "Hello John Doe"

[Vue2]过滤器是Vue组件提供的一种功能,允许您对模板动态数据的任何部分应用格式和转换。

它们不会改变组件的数据或任何东西,但只会影响输出。

假设你正在打印一个名字:

新Vue ({ 埃尔:“#容器”, 数据(){ 返回{ 名称:“玛丽亚”, 姓:“席尔瓦” } }, 过滤器:{ Prepend: (name, lastname, prefix) => { 返回' ${prefix} ${name} ${lastname} ' } } }); < script src = " https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js " > < /脚本> < div id = "容器" > <p>{{name, lastname | prepend('Hello')}}!< / p > < / div >

请注意应用筛选器的语法,即| filterName。如果您熟悉Unix,那就是Unix管道操作符,用于将一个操作的输出作为输入传递给下一个操作。

组件的filters属性是一个对象。 单个过滤器是接受一个值并返回另一个值的函数。

返回值是Vue.js模板中实际打印的值。

在Vue3中删除了过滤器

你需要小心vue/no-side-effects-in-computed-properties ESlint规则,不要在computed内部做任何事情。

与此同时,如果您正在寻找一种记忆方法,您可以阅读这篇文章或使用veuse的ememoize。

或者甚至从Vue3.2开始的v-memo。