Vue.js
Vue.js에서 멀티 인스턴스 사용하기
아이스올리
2024. 4. 18. 18:00
지금 까지는 한개의 Vue로 한개의 인스턴스를 사용하였지만, 여러개의 Vue로 두 개 이상의 인스턴스도 사용이 가능하다.
Vue.js에서 멀티 인스턴스 사용 예
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>여러개의 vue 인스턴스 사용</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
{{ name }}
<br>
<button @click = "change">vue1 변경</button>
</div>
<div id="app-1">
{{ name }}
<br>
<button @click = "change">vue2 변경</button>
</div>
<script>
new Vue({
el: '#app',
data: {
name : 'first'
},
methods: {
change() {
this.name = 'firse vue'
}
}
})
new Vue({
el: '#app-1',
data: {
name : 'second'
},
methods: {
change() {
this.name = 'second vue'
}
}
})
</script>
</body>
</html>
multi-vue.zip
0.00MB
위의 예 처럼 div에 사용되는 id값을 통하여 Vue를 여러개 생성하고 d값을 지정하여 멀티 인스턴스를 사용할 수 가 있다.
더 나아가서 위의 예에서 app에 해당하는 vue에서 app-1에 해당하는 뷰의 데이터 또는 함수를 이용하고 싶을 경우에는 아래의 예와 같이 "const 이름"을 사용하면 된다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>여러개의 vue 인스턴스 사용</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
{{ name }}
<br>
<button @click = "change">vue1 변경</button>
</div>
<div id="app-1">
{{ name }}
<br>
<button @click = "change">vue2 변경</button>
</div>
<script>
const app = new Vue({
el: '#app',
data: {
name : 'first'
},
methods: {
change() {
app1.name = 'firse vue'
}
}
})
const app1 = new Vue({
el: '#app-1',
data: {
name : 'second'
},
methods: {
change() {
this.name = 'second vue'
}
}
})
</script>
</body>
</html>
multi-vue.zip
0.00MB