<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>父子组件传参组件</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="itapp">
<!-- 父组件通过props向下传递数据给子组件 -->
<!-- <my-world :message='msg' :name="name" v-on:e-world='getData()'></my-world> -->
<my-world :message='msg' :name="name" @e-world='getData'></my-world>
<h1>我是父组件</h1>
<!-- {{testName}} -->
<h2>访问自己的数据:{{msg}}</h2>
<h2>访问到子组件的数据:{{testkk}}</h2>
</div>
<template id="world">
<div>
<h1>我是world组件</h1>
<h2>访问我自己的数据sex:{{sex}}</h2>
<h2>访问父组件中的数据:
{{message}}
{{name}}
{{age}}
{{user.username}}
</h2>
<button type="button" @click="send"> 将子组件的数据向上传递给父组件</button>
</div>
</template>
<script>
var childWorld = {
// props:['message','name','age','user'],
props:{
//也可以为对象,允许配置高级设置,类型判断,数据检测,设置默认值
message:String,
name:{
type:String,
required:true
},
age:{
type:Number,
default:18,
validator:function(value){
return value>0
}
},
user:{
type:Object,
default:function(){
//对象或者数组的默认值必须使用函数进行返回
return {
id:100,
username:'秋香'
}
}
}
},
data(){
return {
sex:'male',
height:'190',
testName:'测试',
}
},
methods:{
send(){
this.$emit('e-world',{
testName:this.testName,
sex:this.sex
})
}
},
template:'#world'
};
var vm=new Vue({ //这里的vm也是一个组件,称为根组件Root ,父组件
el:'#itapp',
data(){
return {
msg:'黑客',
name:'tom',
age:23,
user:{id:9527,username:'唐伯虎'},
sex:'',
height:'',
testkk:{}
}
},
components:{
//子组件
'my-world':childWorld
},
methods:{
getData(data){
this.testkk = data;
console.log('sss');
}
}
});
</script>
</body>
</html>
父子组件相互传参
最新推荐文章于 2024-01-10 15:30:57 发布