<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>sync</title>
<script src="../vue.js"></script>
</head>
<body>
<div id="app">
<div class="hello">
//input实时改变wrd的值, 并且会实时改变box里的内容
<input type="text" v-model="wrd">
<box :word.sync="wrd"></box>
</div>
</div>
<script type="text/javascript">
Vue.component('box', {
data() {
return {
str: '',
}
},
props: {
word: ''
},
watch: {
str: function(newValue, oldValue) {
//每当str的值改变则发送事件update:word , 并且把值传过去
this.$emit('update:word', newValue)
}
},
template: `<div class="hello">
<div class="ipt">
<input type="text" v-model="str">
</div>
//word是父元素传过来的
<h2>{{ word }}</h2>
</div>`
});
var vm = new Vue({
el: '#app',
data() {
return {
wrd: ''
}
}
});
</script>
</body>
</html>
from:https://blog.csdn.net/kingov/article/details/78367809