console
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<div id="app">
<h1>父组件</h1>
<div class="hello">
姓名: <input type="text" v-model="obj.name">
</div>
<div class="hello">
年龄: <input type="text" v-model="obj.age">
</div>
<div class="hello">
eat: <input type="text" v-model="obj.food">
</div>
<todo-item :item='objStr' @save-to='savex'></todo-item>
</div>
<script>
Vue.component('todo-item', {
props: ['item'],
template: `
<div>
<h1>子组件</h1>
<div class="hello">
姓名: <input type="text" v-model="strToObj.name">
</div>
<div class="hello">
年龄: <input type="text" v-model="strToObj.age">
</div>
<button @click='save()'>保存</button>
</div>`,
computed: {
strToObj: function () {
console.log(this.item);
return JSON.parse(this.item);
}
} ,
methods:{
save(){
console.log(1,this.strToObj)
this.$emit('save-to',this.strToObj)
}
}
});
new Vue({
el: '#app',
data: {
obj:{
name:'1',
age:'2',
food:'3',
},
objStr:'',
},
methods: {
savex(e){
console.log(2,e.name)
this.obj=e
}
},
watch:{
obj: {
deep: true,//深度监听,可以监听'对象'内部的数据变化
handler: function (newVal,oldVal){
this.objStr = JSON.stringify(this.obj);
},
immediate:true,//初始化监听一次,执行一次handler函数
}
},
})
</script>
</body>
</html>