IT

Vue에서 계산 된 방법과 방법

lottoking 2020. 6. 29. 07:40
반응형

Vue에서 계산 된 방법과 방법


Vue.js에서 메소드와 계산 된 값의 주요 차이점은 무엇입니까?

그들은 동일하고 상호 교환 가능해 보입니다.


Vue에서 계산 된 값과 방법은 매우 다르며 대부분의 경우 상호 교환 할 수 없습니다.

계산 된 재산

계산 된 값에 더 적합한 이름은 계산 된 속성 입니다. 실제로 Vue가 인스턴스화되면 계산 된 속성은 getter 및 때로는 setter를 사용하여 Vue의 속성으로 변환됩니다. 기본적으로 계산 된 값을 계산하는 데 사용되는 기본 값 중 하나가 업데이트 될 때마다 자동으로 업데이트되는 파생 값으로 생각할 수 있습니다. 당신은하지 않습니다 전화 A는 계산이 매개 변수를 허용하지 않습니다. 데이터 속성과 마찬가지로 계산 된 속성을 참조합니다. 다음은 설명서 의 고전적인 예입니다 .

computed: {
  // a computed getter
  reversedMessage: function () {
    // `this` points to the vm instance
    return this.message.split('').reverse().join('')
  }
}

DOM에서 다음과 같이 참조됩니다.

<p>Computed reversed message: "{{ reversedMessage }}"</p>

계산 된 값은 Vue에 존재하는 데이터를 조작하는 데 매우 유용합니다. 데이터를 필터링하거나 변환 할 때마다 일반적으로 해당 목적으로 계산 된 값을 사용합니다.

data:{
    names: ["Bob", "Billy", "Mary", "Jane"]
},
computed:{
    startsWithB(){
        return this.names.filter(n => n.startsWith("B"))
    }
}

<p v-for="name in startsWithB">{{name}}</p>

계산 된 값은 변경되지 않은 경우 다시 계산할 필요가없는 값을 반복적으로 계산하지 않도록 (예를 들어 루프에 없을 수 있으므로) 캐시됩니다.

방법

메소드는 Vue 인스턴스에 바인딩 된 함수일뿐입니다. 명시 적으로 호출 할 때만 평가됩니다. 모든 자바 스크립트 함수와 마찬가지로 매개 변수를 허용하며 호출 될 때마다 다시 평가됩니다. 방법은 모든 기능이 유용한 동일한 상황에서 유용합니다.

data:{
    names: ["Bob", "Billy", "Mary", "Jane"]
},
computed:{
    startsWithB(){
        return this.startsWithChar("B")
    },
    startsWithM(){
        return this.startsWithChar("M")
    }
},
methods:{
    startsWithChar(whichChar){
        return this.names.filter(n => n.startsWith(whichCharacter))
    }
}

Vue의 문서 는 정말 훌륭하고 쉽게 접근 할 수 있습니다. 난 그것을 추천 해.


@gleenk가 메소드와 계산 된 속성 사이의 캐시 및 종속성 차이를 분명하게하기위한 실제적인 예를 요청했을 때 간단한 시나리오를 보여 드리겠습니다.

app.js

new Vue({
    el: '#vue-app',
    data: {
        a: 0,
        b: 0,
        age: 20
    },
    methods: {
        addToAmethod: function(){
            console.log('addToAmethod');
            return this.a + this.age;
        },
        addToBmethod: function(){
            console.log('addToBmethod');
            return this.b + this.age;
        }
    },
    computed: {
        addToAcomputed: function(){
            console.log('addToAcomputed');
            return this.a + this.age;
        },
        addToBcomputed: function(){
            console.log('addToBcomputed');
            return this.b + this.age;
        }
    }
});

여기에는 동일한 작업을 수행하는 2 개의 메서드와 2 개의 계산 속성이 있습니다. 메소드 addToAmethod& addToBmethod및 계산 된 특성 addToAcomputed&은 addToBcomputed모두 + 또는 +에 +20 (즉, age값)을 추가합니다 . 방법에 관해서는, 이들은되는 이라 모든 동작이 수행 된 시간의 어느 한 특정 방식에 대한 종속성이 변경되지 않은 경우에도, 나열된 특성을. 계산 된 속성의 경우 코드는 종속성이 변경된 경우에만 실행됩니다. 예를 들어, A 또는 B를 의미하는 특정 속성 값 중 하나가 트리거 또는 각각.abaddToAcomputedaddToBcomputed

방법과 계산 설명은 꽤 비슷한 것 같다,하지만 @Abdullah 칸이 이미 것처럼 지정 을, 그들은 같은 것이 아니다 ! 이제 HTML을 추가하여 모든 것을 함께 실행하고 차이점이 어디 있는지 살펴 보겠습니다.

방법 사례 데모

new Vue({
    el: '#vue-app',
    data: {
        a: 0,
        b: 0,
        age: 20
    },
    methods: {
        addToAmethod: function(){
            console.log('addToAmethod');
            return this.a + this.age;
        },
        addToBmethod: function(){
            console.log('addToBmethod');
            return this.b + this.age;
        }
    }
});
<!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title>VueJS Methods - stackoverflow</title>
            <link href="style.css" rel="stylesheet" />
            <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.11/vue.min.js"></script>
    
        </head>
        <body>
            <div id="vue-app">
                <h1>Methods</h1>
                <button v-on:click="a++">Add to A</button>
                <button v-on:click="b++">Add to B</button>
                <p>Age + A = {{ addToAmethod() }}</p>
                <p>Age + B = {{ addToBmethod() }}</p>
            </div>
        </body>
        
        <script src="app.js"></script>
    </html>

설명 된 결과

When I click on the button "Add to A", all the methods are called (see the console log screen result above), the addToBmethod() is also executed but I didn't press the "Add to B" button; the property value that refers to B has not changed. The same behaviour comes if we decide to click the button "Add to B", because again both the methods will be called independently of dependency changes. According to this scenario this is bad practice because we are executing the methods every time, even when dependencies have not changed. This is really resource consuming because there is not a cache for property values that have not changed.

method button method

The Computed property case demo

new Vue({
    el: '#vue-app',
    data: {
        a: 0,
        b: 0,
        age: 20
    },

    computed: {
        addToAcomputed: function(){
            console.log('addToAcomputed');
            return this.a + this.age;
        },
        addToBcomputed: function(){
            console.log('addToBcomputed');
            return this.b + this.age;
        }
    }
});
<!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title>VueJS Computed properties - stackoverflow</title>
            <link href="style.css" rel="stylesheet" />
            <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.11/vue.min.js"></script>
        </head>
        <body>
            <div id="vue-app">
                <h1>Computed Properties</h1>
                <button v-on:click="a++">Add to A</button>
                <button v-on:click="b++">Add to B</button>
                <p>Age + A = {{ addToAcomputed }}</p>
                <p>Age + B = {{ addToBcomputed }}</p>
            </div>
        </body>
        
        <script src="app.js"></script>
    </html>

The explained result

When I click on the button "Add to A", only the computed property addToAcomputed is called because, as we already said, the computed properties are executed only when a dependency has changed. And since I didn't press the button "Add to B" and the age property value for B has not changed, there is no reason to call and execute the computed property addToBcomputed. So, in a certain sense, the computed property is maintaining the "same unchanged" value for the B property like a kind of cache. And in this circumstance this is consider good practice.

computed button computed


From the docs

..computed properties are cached based on their dependencies. A computed property will only re-evaluate when some of its dependencies have changed.

If you want data to be cached use Computed properties on the other hand if you don't want data to be cached use simple Method properties.


One of difference between computed and method. Suppose we have a function which will return counter value.(counter is just variable). Let's look how function behaves in both computed and method

Computed

At first time of execution the code inside the function will be executed and vuejs will store the counter value in cache(for accessing faster). But when we are again calling the function vuejs will not again execute the code written inside of that function. It first checks any changes made to the counter or not. If any changes made then only it will re-execute the code which is inside that function. If there are no changes made to the counter vuejs will not again execute the function. It will simply return the previous result from the cache.

Method

This is just like a normal method in the javascript. Whenever we call the method it will always execute the code inside the function irrespective of changes made to the counter.

Method will always reexecutes the code irrespective of changes in the code. where as computed will reexecute the code then only if one of it's dependency's values changed. Otherwise it will give us the previous result from the cache without reexecuting


Computed Properties

Computed properties are called computed value as well. It means, they update and can be changed anytime. Also, it caches the data until it changes. When the Vue is instantiated, computed properties are converted into a property.

One more thing I want to share, You cannot pass any parameter in the computed properties that's why while calling any computer property no parenthesis required.

Methods

Methods are the same as function and work the same way. Besides, a method does nothing unless you call it. Also, like all javascript functions, it accepts parameters and will be re-evaluated every time it’s called. After that, they can’t cache values

In the method calling parenthesis is there and you can send one or more parameter in that.


Here’s a breakdown of this question.

When to use methods

  • To react to some event happening in the DOM
  • To call a function when something happens in your component.
  • You can call a method from computed properties or watchers.

When to use computed properties

  • You need to compose new data from existing data sources
  • You have a variable you use in your template that’s built from one or more data properties
  • You want to reduce a complicated, nested property name to a more readable and easy to use one (but update it when the original property changes)
  • You need to reference a value from the template. In this case, creating a computed property is the best thing, because it’s cached.
  • You need to listen to changes of more than one data property

참고URL : https://stackoverflow.com/questions/44350862/method-vs-computed-in-vue

반응형