组件的使用
组件传值
- 组件是单独封装的模块,拥有自己的data html模块
- 组件中不可以访问vue实例中的data数据,不建议在里面访问vue实例对象
- 组件中data中的数据必须以方法函数的方式返回数据,好处是函数可以直接返回一个对象,每一次返回数据对象都不一样,这样可以让数据不受影响
父组件与子组件间的传值
props传值
-
props传值方法一
props:[`title`,'st'],
-
props传值方法二
props:{
title:Array,
st:String,
t1:{
type:String,
default:'這個是默认数据没有填写的时候'
// 数据类型为数组或者是对象的时候默认数据值需要为函数
}}
props传值属性做類型限制
-
是否传值限制
required:true
-
做默认数据
props:{ title:Array, st:String, t1:{ type:String, default:'這個是默认数据没有填写的时候' // 数据类型为数组或者是对象的时候默认数据值需要为函数 }}
注意:数据类型为数组或者是对象的时候默认数据值需要为函数
例如:
t2:{ type:Array, default: function (){ return{ t2:'hello' } }}
-
限制传值类型
props:
{title:Array,
st:String,
}}
源代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>组件的构建</title>
</head>
<!--组件是单独封装的模块,拥有自己的data html模块-->
<!--组件中不可以访问vue实例中的data数据,不建议在里面访问vue实例对象-->
<!--组件中data中的数据必须以方法函数的方式返回数据,好处是函数可以直接返回一个对象,每一次返回数据对象都不一样,这样可以让数据不受影响-->
<body>
<div id="app2">
<cpn v-bind:title = "tmsg" :st="str"></cpn>
<cpn v-bind:title = "tmsg" :st="str" :t2 ='t2msg'></cpn>
</div>
<!--方法一写在script里面-->
<script type="text/x-template" id="cpn">
<div>
<h1>hhhhhhhhhh{{title}}</h1>
<h5>{{st}}</h5>
<h5>{{t1}}</h5>
<h5>{{t2}}</h5>
</div>
</script>
<!--方法二直接使用template标签-->
<script src="../vue.js"></script>
<script>
<!-- 创建组件构造对象-->
const cpn=('#cpn',{template: `#cpn`,
//做類型限制
//做默认数据
//是否传值限制
props:{
title:Array,
st:String,
t1:{
type:String,
default:'這個是默认数据没有填写的时候'
// 数据类型为数组或者是对象的时候默认数据值需要为函数
},
t2:{
type:Array,
default: function (){
return{
t2:'hello'
}
},
required:true
}
// 必须设置要给默认数据requierd
},
data(){
return{
}
}}
)
let app=new Vue({
el:'#app2',
data:{
str:'jiayou',
tmsg:['kk','aa','ww'],
stmsg:'hhh',
t1msg: '' ,
t2msg:[11,22,334]
},
components:{cpn}
})
</script>
</body>
</html>