在有些情況下,我們可能需要對一個 prop 進行“雙向綁定”。也就是想實現在子組件中改變值,父組件中的值也能隨着變化
不用sync的
父組件
<template>
<div id="app">
<blog :num="d" @change="d = $event"></blog>{{d}}
</div>
</template>
<script>
import Blog from './components/Blog'
export default {
name: 'app',
data () {
return {
d:1
}
},
components: {
Blog
}
}
</script>
<style>
@import "assets/css/base.css";
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
子組件
<template>
<button @click="fn">{{cur}}</button>
</template>
<script>
export default {
name: "blog",
props: ['num'],
data(){
return {
cur: 1
}
},
created(){
this.cur = this.num
},
methods:{
fn(){
this.cur ++
this.$emit('change',this.cur)
}
}
}
</script>
<style scoped>
</style>
使用sync
父組件中改變這一句
<blog :num.sync="d"></blog>{{d}}
子組件中改變這一句
this.$emit('update:num',this.cur)