- .sync修飾組件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue-03</title>
<!-- 引入Vue -->
<link href="https://cdn.bootcss.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.bootcss.com/vue/2.5.16/vue.js"></script>
</head>
<body>
<div class="container" style="margin-top: 12px;">
<div id="demo" class="row">
{{ say }}
<br />
<my-input :value.sync="say"></my-input>
</div>
</div>
<script>
new Vue({
el: '#demo',
data: {
say: "123"
},
components: {
"my-input": {
props: ['value'],
template: "<div><input v-bind:value='value' v-on:input='change1' />{{value}}</div>",
watch: {
value: function(newValue, oldValue) {
alert('子組件value新舊值' + newValue + '/' + oldValue);
//this.$emit('update:value', newValue)
}
},
methods: {
change1: function(e) {
var v = e.target.value
this.$emit('update:value', v)
},
}
}
},
watch: {
say: function(n, o) {
alert('父組件新舊值' + n + '-' + o)
}
},
methods: {
}
})
</script>
</body>
- v-model修飾組件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue-10</title>
<!-- 引入Vue -->
<link href="https://cdn.bootcss.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.bootcss.com/vue/2.5.16/vue.js"></script>
</head>
<body>
<div class="container" style="margin-top: 12px;">
<div id="demo" class="row">
{{ say }}
<br />
<my-input v-model="say"></my-input>
</div>
</div>
<script>
new Vue({
el: '#demo',
data: {
say: "123"
},
components: {
"my-input": {
props: ['value'],
template: "<div><input v-bind:value='value' v-on:input='change' />{{value}}</div>",
watch: {
value: function(newValue, oldValue) {
alert('子組件value新舊值' + newValue + '/' + oldValue);
//this.$emit('update:value', newValue)
}
},
methods: {
change: function(e) {
this.$emit('input', e.target.value)
}
}
}
}
})
</script>
</body>
區別只能本身慢慢體會,我的感受 .sync用法靈活,而v-model只能接受prop名爲爲value的值. 二者都須要手動觸發$emit方法.