1.子元素中的数据传给父元素,父元素需要接收,子元素需要触发绑定的事件
简单的例子
<body>
<div id="app">
<my-father>
</my-father>
</div>
<script src="js/vue.js"></script>
<script>
//父级
Vue.component('my-father',{
template:`
<div>
<my-child @send="rev"> <!--//绑定父元素中的事件-->
</my-child>
<a href="#">{{msg}}</a>
</div>
`,
data:function(){
return{
msg:"" //创建一个假数据
}
},
methods:{
rev:function(txt){
this.msg=txt //接受子元素传过来的·参数,把假数据变真数据
}
}
})
//子级
Vue.component('my-child',{
template:`
<button @click="send">按钮</button>
<!--//点击触发子元素中的事件-->
`,
data:function(){
return{
mass:"我是子组件中的内容"
}
},
methods:{
send:function(){
this.$emit('send',this.mass) //传递子元素中的内容
}
}
})
new Vue({
el:"#app"
})
//效果:点击按钮,显示子组件内容
</script>
</body>
2.input中的子传父例子
<body>
<div id="app">
<my-father>
</my-father>
</div>
<script src="js/vue.js"></script>
<script>
Vue.component('my-father',{
template:`
<div>
<h1>我是父组件</h1>
<h2>{{arr}}</h2>
<a href="#"> 这里是父级内容{{msg}}</a>
<my-child @send="rev"> <!--//绑定父元素中的事件-->
</my-child>
</div>
`,
data:function(){
return{
msg:""
//创建一个假数据
}
},
methods:{
rev:function(txt){
this.msg=txt //接受子元素传过来的·参数,把假数据变真数据
}
}
})
Vue.component('my-child',{
template:`
<div>
<h1>这是子组件</h1>
<input v-model="mass">
<button @click="send">传递给父级</button>
</div>
<!--//点击触发子元素中的事件-->
`,
data:function(){
return{
mass:""
}
},
methods:{
send:function(){
this.$emit('send',this.mass) //传递子元素中的内容
}
}
})
new Vue({
el:"#app"
})
</script>
</body>
网友评论