是否有可能在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.js的方式,或者你做的方式是错误的。

然而,在某些情况下,您需要这样做。我将向您展示一个使用getter和setter将值传递给计算属性的简单示例。

<template>
    <div>
        Your name is {{get_name}} <!-- John Doe at the beginning -->
        <button @click="name = 'Roland'">Change it</button>
    </div>
</template>

还有剧本

export default {
    data: () => ({
        name: 'John Doe'
    }),
    computed:{
        get_name: {
            get () {
                return this.name
            },
            set (new_name) {
                this.name = new_name
            }
        },
    }    
}

当单击按钮时,我们将名称“Roland”传递给计算属性,在set()中,我们将名称从“John Doe”更改为“Roland”。

下面是计算与getter和setter一起使用的常见用例。 假设你有以下vuex商店:

export default new Vuex.Store({
  state: {
    name: 'John Doe'
  },
  getters: {
    get_name: state => state.name
  },
  mutations: {
    set_name: (state, payload) => state.name = payload
  },
})

在你的组件中,你想要添加v-model到一个输入,但使用vuex存储。

<template>
    <div>
        <input type="text" v-model="get_name">
        {{get_name}}
    </div>
</template>
<script>
export default {
    computed:{
        get_name: {
            get () {
                return this.$store.getters.get_name
            },
            set (new_name) {
                this.$store.commit('set_name', new_name)
            }
        },
    }    
}
</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中删除了过滤器

您可以使用方法,但我仍然倾向于使用计算属性而不是方法,如果它们不会改变数据或没有外部影响的话。

你可以通过这种方式将参数传递给计算属性(没有文档,但由维护者建议,不记得在哪里):

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

编辑:请不要使用此解决方案,它只会使代码复杂化,没有任何好处。

我想首先重申前面的警告,使用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>

是的方法是用来使用参数的。就像上面的答案一样,在你的例子中,最好使用方法,因为执行非常轻。

仅供参考,在方法复杂且成本较高的情况下,可以这样缓存结果:

data() {
    return {
        fullNameCache:{}
    };
}

methods: {
    fullName(salut) {
        if (!this.fullNameCache[salut]) {
            this.fullNameCache[salut] = salut + ' ' + this.firstName + ' ' + this.lastName;
        }
        return this.fullNameCache[salut];
    }
}

注意:使用此方法时,如果处理的是数千,请注意内存