组件之间的数据传递 示例

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>组件之间的数据传递</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="js/vue.js"></script>
<!--<script src="bil/jquery.min.js"></script>-->
<script>

window.onload=function (){
//配置是否允许vue-devtools检查代码,方便调试,生产环境中需要设置为false
Vue.config.devtools=false;
Vue.config.productionTip=false;//阻止vue启动时生成生产消息
new Vue({
el:"#container",
data:{
flag:"组件名"
},
components:{
'my-hello':{
template:'#hello',
data:function(){
return {
msg:"网博",
age:22,
user:{
id:1,
username:"小零"
},
sex:"",
height:0
}
},
methods:{
getData(sex,height){
this.sex=sex,
this.height=height,
console.log(sex, height);
}
},
components:{
'my-world':{
template:'#world',
// props:['message','nickname'],//简单的字符串数组
props:{//也可以是对象,允许配置高级设置,如类型判断,数据校验,默认值
message:String,
nickname:{
type:String,
required:true//必须传
}
/**type:String,Number,Boolean,Array,Object,Date,Function,Symbol*/
},
data:function(){
return {
sex:"male",
height:180.5
}
},
methods:{
send(){
//this:这里的this指的是当前my-world组件
this.$emit('e-world',this.sex,this.height)
}
}
}
}
}
}

})
}
</script>
</head>
<body>
<div id="container">
<my-hello>
<!--子组件只能在父组件内部使用:<my-world></my-world> (错误使用)-->
</my-hello>
</div>

<template id="hello">
<div>
<h2>我是hello 父组件</h2>
<div>访问自己的数据:{{msg}},{{age}},{{user.username}}</div>
<div>访问子组件的数据:{{sex}},{{height}}</div>

<!--子组件只能在父组件内部使用-->
<my-world :message="msg" :nickname="user.username" @e-world="getData"></my-world>

</div>
</template>
<template id="world">
<div>
<h2>我是world 子组件</h2>
<hr>
<h4>访问父组件中的数据:{{message}},{{nickname}}</h4>
<hr>
<h4>访问自己的数据:{{sex}},{{height}}</h4>
<button @click="send">将子组件的数据传递给父组件</button>
</div>
</template>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/yuezhen/p/10408243.html