VUE--元件間v-model繫結
阿新 • • 發佈:2021-01-26
1、自定義指令
// 父元件-html
<template>
<div>
<my-son v-my-model="parentValue"></my-son>
// 支援告知指令子元件接收變數名為"sonValue"(預設為"value")
<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>
// 子元件-html-預設value
<template>
<div>
{ {value}}
</div>
</template>
<script>
export default {
data() {
return {
value: "",
}
},
}
</script>
// 子元件-html-指定sonValue
<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) {
// emit
Vue.set(parent, data.expression, sonVal);
} else {
// get
Vue.set(son, sonKey, data.value);
}
})
2、子元件監聽
// 父元件-html
<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>
// 子元件-html
<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>