要实现的功能:
点击【显示子组件】按扭,子组件显示----已实现
点击【关闭】,子组件关闭----未实现;第一次点击报underfind错误?,并且子组件没有隐藏
点击【确认】按钮把input中的值传到父组件的 {{text}} ------未实现
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script type="text/javascript" src="https://cdn.bootcss.com/vue/2.3.0/vue.js"></script>
</head>
<body>
<template id="aa">
<div>
<hr>
我是子组件2
<input type="text" v-model="text2">
<button @click="close()">关闭</button>
<button @click="affirm()">确认</button>
</div>
</template>
<div id="box">
<p>
我是父组件:{{text}}
<button @click="showChild()">显示子组件</button>
</p>
<child-page v-show="pageSwitch" :pageSwitch2="pageSwitch" :text2="text"></child-page>
</div>
<script>
new Vue({
el:"#box",
data:{
text:"hello",
pageSwitch:false
},
methods:{
showChild:function(){
this.pageSwitch=true;
}
},
components:{
"child-page":{
template:"#aa",
data:function(){
return{
childmsg:"子组件信息"
}
},
props:['pageSwitch2',"text2"],
methods:{
close:function(){
console.log(this.pageSwitch2);
console.log(this.text2);
this.pageSwitch2=false;
},
affirm:function(){
console.log(this.pageSwitch2);
console.log(this.text2);
}
}
}
}
})
</script>
</body>
</html>
用vuex吧,也就是单一事件中心管理组件通信
你报错的原因应该是你通过子组件修改了父组件的数据,这在vue2.0是不允许的(1.0可以),你要是想只是不报错,可以使用 mounted中转,但解决不了实际问题。所以可以父组件每次传一个对象给子组件, 对象之间引用
像上面这样,父组件传递数据对象给子组件,子组件修改数据对象里的内容。