<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>props的双向绑定</title>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
<div id="myapp">
<!-- 实现props属性的双向绑定,但是违背了props的单向数据流原则 -->
<child v-bind:age.sync = "total"></child>
{{total}}
</div>
</body>
<script type="text/javascript">
var child = {
template:'<button v-on:click="incream">+1</button>',
props:['age'],
methods:{
incream:function(){
// 子组件触发更新事件this.$emit('update:propsname',newVal);
this.$emit('update:age',this.age+1);//事件的触发
}
}
}
var app = new Vue({
el:"#myapp",
data:{
total:0
},
methods:{
},
components:{
child,
},
})
</script>
</html>
关键代码:
<child v-bind:age.sync = "total"></child>
methods:{
incream:function(){
// 子组件触发更新事件
//this.$emit('update:propsName',newVal);
this.$emit('update:age',this.age+1);//事件的触发
}
}
这样实现props的双向绑定违背了props的单向数据流原则,不推荐使用(.sync在vue2.3推出)