我可以在Vue.Js

时间:2016-11-10 08:06:34

标签: javascript vue.js vuejs2

这可以在Vue.Js中传递计算属性中的参数。我可以看到当getter / setter使用computed时,他们可以获取一个参数并将其分配给变量。像这里documentation

// ...
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未捕获TypeError:fullName不是函数(...)

我应该为这种情况使用方法吗?

11 个答案:

答案 0 :(得分:151)

很可能你想使用方法

<span>{{ fullName('Hi') }}</span>

methods: {
  fullName(salut) {
      return `${salut} ${this.firstName} ${this.lastName}`
  }
}

更长的解释

从技术上讲,您可以使用带有如下参数的计算属性:

computed: {
   fullName() {
      return salut => `${salut} ${this.firstName} ${this.lastName}`
   }
}

(感谢Unirgy获取此基本代码。)

计算属性和方法之间的区别在于计算属性被缓存,并且仅在其依赖关系发生更改时才会更改。 方法会在每次调用时进行评估

如果需要参数,在这种情况下,使用计算属性函数通常没有优势。虽然它允许你将参数化的getter函数绑定到Vue实例,但是你失去了缓存,所以实际上没有任何增益,事实上,你可能会破坏反应性(AFAIU)。您可以在Vue文档https://vuejs.org/v2/guide/computed.html#Computed-Caching-vs-Methods

中阅读有关此内容的更多信息

唯一有用的情况是必须使用getter并且需要对其进行参数化。这种情况发生在例如 Vuex 中。在Vuex中,它是从商店同步获取参数化结果的唯一方法(操作是异步的)。因此,这种方法由官方Vuex文档列出其getter https://vuex.vuejs.org/guide/getters.html#method-style-access

答案 1 :(得分:20)

你可以使用方法,但我更喜欢使用计算属性而不是方法,如果它们没有变异数据或没有外部效果。

您可以通过这种方式将参数传递给计算属性(未记录,但维护人员建议,不记得在哪里):

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

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

答案 2 :(得分:6)

从技术上讲,我们可以将参数传递给计算函数,就像我们可以将参数传递给vuex中的getter函数一样。这样的函数是一个返回函数的函数。

例如,在商店的吸气剂中:

{
  itemById: function(state) {
    return (id) => state.itemPool[id];
  }
}

此getter可以映射到组件的计算函数:

computed: {
  ...mapGetters([
    'ids',
    'itemById'
  ])
}

我们可以在模板中使用这个计算函数,如下所示:

<div v-for="id in ids" :key="id">{{itemById(id).description}}</div>

我们可以应用相同的方法来创建一个带参数的计算方法。

computed: {
  ...mapGetters([
    'ids',
    'itemById'
  ]),
  descriptionById: function() {
    return (id) => this.itemById(id).description;
  }
}

在我们的模板中使用它:

<div v-for="id in ids" :key="id">{{descriptionById(id)}}</div>

话虽如此,我并不是说这是与Vue合作的正确方式。

但是,我可以观察到,当商店中具有指定ID的项目发生变异时,视图会使用此项目的新属性自动刷新其内容(绑定似乎正常工作)。

答案 3 :(得分:1)

  

您可以传递参数,但这不是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
  },
})

在您的组件中,您想使用vuex存储将v-model添加到输入中。

<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>

答案 4 :(得分:1)

可以考虑具有计算功能。因此,对于检定的一个例子,您可以明确地执行以下操作:

    methods: {
        validation(attr){
            switch(attr) {
                case 'email':
                    const re = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
                    return re.test(this.form.email);
                case 'password':
                    return this.form.password.length > 4
            }
        },
        ...
    }

您将使用哪种方式:

  <b-form-input
            id="email"
            v-model="form.email"
            type="email"
            :state="validation('email')"
            required
            placeholder="Enter email"
    ></b-form-input>

请记住,您仍然会错过特定于计算的缓存。

答案 5 :(得分:1)

我想首先重申之前的警告,即使用带有参数的计算(已缓存)只会使计算结果不被缓存,实际上只是使其成为一种方法。

但是,话虽如此,以下是我能想到的所有变体,它们可能有边缘情况可供使用。如果您将其剪切并粘贴到演示应用程序中,则应该清楚发生了什么:

<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>

答案 6 :(得分:0)

是的方法是使用参数。与上述答案一样,在您的示例中,最好使用方法,因为执行非常轻松。

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

colourSegment

注意:使用此功能时,如果处理数千个

,请注意内存

答案 7 :(得分:0)

您还可以通过返回函数将参数传递给getter。当您要查询存储中的数组时,这特别有用:

getters: {
  // ...
  getTodoById: (state) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }

请注意,通过方法访问的getter会在您每次调用它们时运行,并且结果不会被缓存。

这称为方法样式访问,它称为is documented on the Vue.js docs

答案 8 :(得分:0)

computed: {
  fullName: (app)=> (salut)=> {
      return salut + ' ' + this.firstName + ' ' + this.lastName    
  }
}

何时使用

<p>{{fullName('your salut')}}</p>

答案 9 :(得分:0)

过滤器是Vue组件提供的功能,可让您将格式设置和转换应用于模板动态数据的任何部分。

它们不会更改组件的数据或其他任何内容,而只会影响输出。

假设您要打印名称:

new Vue({
  el: '#container',
  data() {
    return {
      name: 'Maria',
      lastname: 'Silva'
    }
  },
  filters: {
    prepend: (name, lastname, prefix) => {
      return `${prefix} ${name} ${lastname}`
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="container">
  <p>{{ name, lastname | prepend('Hello') }}!</p>
</div>

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

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

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

答案 10 :(得分:-1)

我不完全确定你想要实现的目标,但看起来你会使用方法而不是计算完美!

相关问题