web/Vue.js
[Vue.js 기초] 버튼 클릭 시, text 변경
혬혬
2020. 8. 25. 10:19
728x90
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <!--vue-->
</head>
<body>
<div id="app">
<h1>{{msg}}</h1>
<button v-on:click="bbq">hey</button>
</div>
<script>
const app=new Vue({
el:"#app",
data(){
return {
msg:"helloworld",
nextMsg:"happy?"
}
},
methods:{ //함수정의
bbq(){
this.msg=this.nextMsg //this접근유의
}
}
})
</script>
</body>
</html>
클릭시 값이 변경된다는 것은 onclick 이벤트를 추가하는 것과 동일하다.
vue에서는 onclick 이벤트를 추가하기 위해
첫번째, 이번트를 추가할 버튼에 v-on:click="함수명"을 명시해줘야된다.
두번째, Vue 객체를 선언할 때, methods:{~~} 를 선언하여 함수를 선언한다.
단, 여기서 자신의 객체를 접근할 때는 꼭 this를 사용해야된다.
728x90