console
let child = {
template: `
<div>
<input type="text" v-model="model.age"/>
<input type="text" v-model="model.name"/>
<input type="text" v-model="model.address.province"/>
<input type="text" v-model="model.address.city"/>
</div>`,
data() {
return {
model: {
name: "",
age: "",
address : {
province: "",
city: ""
}
}
};
},
props:{
value: {
type: Object,
default: () => { return {};}
}
},
watch:{
value(val) {
console.log("props value change");
Object.keys(val).forEach(key => {
if (this.model[key] !== undefined) {
this.model[key] = val[key];
}
});
},
model :{
handler(val) {
console.log(JSON.stringify(this.cloneModel()));
this.$emit("input", this.cloneModel());
},
deep: true
}
},
methods: {
cloneModel() {
return Object.keys(this.model).reduce((pre, val) => {
pre[val] = this.model[val];
return pre;
}, {});
}
},
mounted() {
Object.keys(this.value).forEach(key => {
if (this[key] !== undefined) {
this[key] = val[key];
}
});
}
};
let child2 = {
template: `
<h2>child2</h2> `,
data(){
return {};
}
}
new Vue({
el:"#app",
methods: {
},
data:{
childData: { },
currentView: "child"
},
mounted() {
this.childData = {
name: "黎明",
age: 18,
address: {
province: "广东",
city: "中山"
}
};
},
components: {
child,
child2
},
methods: {
changeView() {
this.currentView = this.currentView === "child" ? "child2" : "child";
}
}
});
<script src="//cdn.bootcss.com/vue/2.3.4/vue.js">
</script>
<div id="app">
<button @click="changeView">changeView</button>
<hr />
<compontent :is="currentView" v-model="childData"></compontent>
<p>
{{childData}}
</p>
</div>
body {
background: #333;
color: #aaa;
}
h3 {
color: #fff;
border-bottom: 1px dashed #FFF;
padding: 10px 0px;
}