1.カスタム手順
<template>
<div>
<my-son v-my-model="parentValue"></my-son>
<my-son v-my-model:sonValue="parentValue"></my-son>
</div>
</template>
<script>
import mySon from "./mySon.vue"
export default {
components: {
mySon},
data() {
return {
parentValue: "改我试试!",
}
}
}
</script>
<template>
<div>
{
{
value}}
</div>
</template>
<script>
export default {
data() {
return {
value: "",
}
},
}
</script>
<template>
<div>
{
{
sonValue}}
</div>
</template>
<script>
export default {
data() {
return {
sonValue: "",
}
},
}
</script>
import Vue from "vue";
Vue.directive("myModel", function (el, data) {
let son = el.__vue__;
let parent = son.$parent;
let sonKey = data.arg ? data.arg : "value";
let sonVal = son[sonKey];
if (data.hasOwnProperty("oldValue") && sonVal !== data.oldValue) {
Vue.set(parent, data.expression, sonVal);
} else {
Vue.set(son, sonKey, data.value);
}
})
2.サブコンポーネントの監視
<template>
<div>
<my-son v-model="parentValue"></my-son>
</div>
</template>
<script>
import mySon from "./components/test"
export default {
components: {
mySon},
data() {
return {
parentValue: "改我试试!",
}
}
}
</script>
<template>
<div>
{
{
sonValue}}
</div>
</template>
<script>
export default {
props:["value"],
computed: {
sonValue:{
get(){
return this.value;
},
set(newVal, oldVal){
if(newVal === oldVal) return;
this.$emit("input", newVal);
}
}
}
}
</script>