1、通過關鍵字sync進行綁定
<!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>Document</title>
</head>
<body>
<div id="app">
<p>父組件:{{ title }}</p>
<hr>
<custon :title.sync="title" :cunt.sync='cunt'></custon>
</div>
</body>
<script src="./vue.js"></script>
<script>
/*
對props進行雙向綁定
sync關鍵字 update是固定寫法關鍵字-----this.$emit('update:cunt','str')
*/
Vue.component('custon',{
props:['title','cunt'],
template:`
<div class="box">
<h2>{{ title }}</h2>
<div>
{{cunt}}
</div>
<button @click="cheng">
按鈕
</button>
</div>
`,
methods:{
cheng(){
console.log("123")
this.$emit('update:title','子組件改變')
this.$emit('update:cunt','2')
}
}
})
new Vue({
el:"#app",
data:{
title:'父組件的title',
cunt:1
}
})
</script>
</html>
2、通過v-model對組件進行綁定
<!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>Document</title>
</head>
<body>
<div id="app">
<p>父組件:{{ obj.title }}</p>
<hr>
<custon v-model='obj'></custon>
</div>
</body>
<script src="./vue.js"></script>
<script>
/*
這里的v-model是屬於一個自定義的綁定
title是綁定的數據
子組件通過 props來接收一個value
子組件通過$emit來綁定input事件來進行雙向綁定----this.$emit('input','子組件改變')
*/
Vue.component('custon',{
props:['value'],
template:`
<div class="box">
<h2>{{ value.title }}</h2>
<div>{{ value.center }}</div>
<div>{{ value.sum }}</div>
<button @click="cheng">
按鈕
</button>
</div>
`,
data(){
return {
Zobj:{}
}
},
methods:{
cheng(){
console.log(this.value)
let objs = {
title:'子組件title',
center:'子組件內容',
sum:"bbb"
}
this.$emit('input',objs)
}
}
})
new Vue({
el:"#app",
data:{
obj:{
title:'父組件title',
center:'父組件內容',
sum:'aaa'
},
}
})
</script>
</html>
3、通過v-model和組件進行綁定,傳輸一個對象
<!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>Document</title>
</head>
<body>
<div id="app">
<p>父組件:</p>
<p>1、{{ arr.list[0] }}</p>
<p>2、{{ arr.list[1] }}</p>
<p>{{arr.bbq}}</p>
<hr>
<custon v-model='arr'></custon>
</div>
</body>
<script src="./vue.js"></script>
<script>
/*
這里的v-model是屬於一個自定義的綁定
arr是綁定的數據
子組件通過 props來接收一個value
子組件通過$emit來綁定input事件來進行雙向綁定----this.$emit('input','子組件改變')
*/
Vue.component('custon',{
props:['value'],
template:`
<div class="box">
{{value}}
<button :class="value.list[0]" @click="cheng">
按鈕
</button>
</div>
`,
methods:{
cheng(){
console.log(this.value)
let arr2 = {
list:this.value.list.reverse(),
bbq:!this.value.bbq
}
this.$emit('input',arr2,)
}
}
})
new Vue({
el:"#app",
data:{
arr:{
list:['a','b'],
bbq:false
}
},
updated(){
console.log("數據發生了改變")
console.log(this.arr.bbq)
}
})
</script>
<style>
.a{
display:block;
width:50px;
height:50px;
background:#FAF;
}
.b{
display:block;
width:50px;
height:50px;
background:#F60;
}
</style>
</html>
