VueJs의 메소드 소개

8005 단어 vuejavascript
지난 기사에서 우리는 Vue로 여행을 시작했고, 더 깊이 들어가 우리에게 매우 유용한 메서드를 소개할 것입니다. 이 기사에서는 간단한 방법만 볼 것입니다.

vue에서는 이벤트 없이도 메서드를 시작할 수 있습니다. 예를 들면 다음과 같습니다.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <!-- importing vue js dev library -->
    <!-- development version, includes helpful console warnings -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <title>My vue Test</title>
</head>
<body>
    <div id="app">
        {{ sayHello() }}
    </div>
    <script type="text/javascript">
        var app = new Vue({ //instantiating the vue instance
          el: '#app', //we select where vue is going to work in the DOM
          data: {
            name: 'Mattia'//this are the data
          },
          methods: {
            sayHello: function() {
                return "Hello there, " +this.name;
            }
          }
        })
    </script>
</body>
</html>


이것은 결과 페이지입니다.


이벤트 처리



"v-on:"지시어를 사용하여 데이터를 변경하거나 함수를 호출할 수 있습니다. Vue의 디렉티브는 다른 HTML 요소에 할당할 수 있는 속성과 같습니다.
예를 들어 이 특정 버튼은 sayHello 메소드에 표시된 이름을 변경합니다.

<button v-on:click="name = 'Miyazaky'">My name is Miyazaky!</button>


물론 메서드는 여러 줄의 코드를 가질 수 있습니다. 이 경우 이름을 사용하여 함수를 호출할 수 있습니다.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <!-- importing vue js dev library -->
    <!-- development version, includes helpful console warnings -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <title>My vue Test</title>
</head>
<body>
    <div id="app">
        {{ sayHello() }}
        <br>
        <button v-on:click="changeName()">My name isn't {{ name }}!</button>
    </div>
    <script type="text/javascript">
        var app = new Vue({ //instantiating the vue instance
          el: '#app', //we select where vue is going to work in the DOM
          data: {
            name: 'Mattia'//this are the data
          },
          methods: {
            sayHello: function() {
                return "Hello there, " +this.name;
            },

            changeName: function() {
                if (this.name === "Mattia") {
                    this.name = "Miyazaki"; 
                } else {
                    this.name = "Mattia";
                }
            }
          }
        })
    </script>
</body>
</html>

좋은 웹페이지 즐겨찾기