development

Vue.Js의 계산 속성에서 매개 변수를 전달할 수 있습니까

big-blog 2020. 6. 21. 19:06
반응형

Vue.Js의 계산 속성에서 매개 변수를 전달할 수 있습니까


Vue.Js의 계산 속성에서 매개 변수를 전달할 수 있습니다. 계산 된 것을 사용하여 getter / setter가있을 때 매개 변수를 가져 와서 변수에 할당 할 수 있습니다. 문서 에서 여기처럼 :

// ...
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    
  }
}
// ...

계산 된 속성은 인수를 사용하여 원하는 출력을 반환합니다. 그러나 이것을 시도하면이 오류가 발생합니다.

vue.common.js : 2250 Uncaught TypeError : fullName은 함수가 아닙니다 (…)

그러한 경우에 방법을 사용해야합니까?


아마도 방법을 사용하고 싶을 것입니다.

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

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

더 긴 설명

기술적으로 다음과 같은 매개 변수와 함께 계산 된 특성을 사용할 수 있습니다.

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

(이에 Unirgy대한 기본 코드를 주셔서 감사 합니다.)

계산 된 속성과 메서드의 차이점은 계산 된 속성이 캐시 되어 종속성이 변경 될 때만 변경 된다는 것입니다. 방법은이 호출 할 때마다 평가합니다 .

매개 변수가 필요한 경우 일반적으로 이러한 경우 메서드보다 계산 된 속성 함수를 사용하면 이점이 없습니다. Vue 인스턴스에 바인딩 된 getter 함수를 매개 변수화 할 수는 있지만 캐싱을 잃어 실제로 아무런 이득을 얻지 못하므로 실제로는 반응성이 깨질 수 있습니다 (AFAIU). Vue 문서 https://vuejs.org/v2/guide/computed.html#Computed-Caching-vs-Methods 에서 이에 대한 자세한 내용을 볼 수 있습니다.

유용한 상황은 게터 사용해야하고 매개 변수화해야하는 경우입니다. 이 상황은 예를 들어 Vuex 에서 발생 합니다. Vuex에서는 상점에서 매개 변수화 된 결과를 동 기적으로 얻을 수있는 유일한 방법입니다 (동작은 비동기 임). 따라서이 방법은 공식 Vuex 설명서에 나와 있으며 getter https://vuex.vuejs.org/guide/getters.html#method-style-access


메서드를 사용할 수 있지만 데이터를 변경하지 않거나 외부 효과가없는 경우 메서드 대신 계산 된 속성을 사용하는 것이 좋습니다.

이 방법으로 계산 된 속성에 인수를 전달할 수 있습니다 (문서화되어 있지 않지만 관리자가 제안한 위치는 기억하지 않습니다).

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

편집 :이 솔루션을 사용하지 마십시오, 그것은 아무런 이점없이 코드를 복잡하게합니다.


기술적으로 말하자면 vuex에서 매개 변수를 getter 함수에 전달할 수있는 것과 같은 방법으로 매개 변수를 계산 함수에 전달할 수 있습니다. 이러한 함수는 함수를 반환하는 함수입니다.

예를 들어, 상점 게터에서 :

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

이 게터는 컴포넌트의 계산 된 함수에 매핑 될 수 있습니다 :

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를 가진 항목이 상점에서 변경되면보기 가이 항목의 새로운 속성으로 내용을 자동으로 새로 고칩니다 (바인딩은 제대로 작동하는 것 같습니다).


You can pass parameters but either it is not a vue.js way or the way you are doing is wrong.

However there are cases when you need to do so.I am going to show you a simple example passing value to computed property using getter and setter.

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

And the script

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

When the button clicked we are passing to computed property the name 'Roland' and in set() we are changing the name from 'John Doe' to 'Roland'.

Below there is a common use case when computed is used with getter and setter. Say you have the follow vuex store:

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

And in your component you want to add v-model to an input but using the vuex store.

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

Filters are a functionality provided by Vue components that let you apply formatting and transformations to any part of your template dynamic data.

They don’t change a component’s data or anything, but they only affect the output.

Say you are printing a name:

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>

Notice the syntax to apply a filter, which is | filterName. If you're familiar with Unix, that's the Unix pipe operator, which is used to pass the output of an operation as an input to the next one.

The filters property of the component is an object. A single filter is a function that accepts a value and returns another value.

The returned value is the one that’s actually printed in the Vue.js template.


Computed could be consider has a function. So for an exemple on valdiation you could clearly do something like :

    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
            }
        },
        ...
    }

Which you'll be using like :

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

Just keep in mind that you miss still miss the caching specific to computed.


Yes methods are there for using params. Like answers stated above, in your example it's best to use methods since execution is very light.

Only for reference, in a situation where the method is complex and cost is high, you can cache the results like so:

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

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

note: When using this, watchout for memory if dealing with thousands


You can also pass arguments to getters by returning a function. This is particularly useful when you want to query an array in the store:

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

Note that getters accessed via methods will run each time you call them, and the result is not cached.

That is called Method-Style Access and it is documented on the Vue.js docs.


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

when you want use

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

I am not fully sure what you are trying to achieve but looks like you will be perfectly fine using method instead of computed!

참고URL : https://stackoverflow.com/questions/40522634/can-i-pass-parameters-in-computed-properties-in-vue-js

반응형