Vue - prop
prop作用
prop的作用是父组件单向传递数据给子组件。
静态传递
子组件
<tenplate>
<div>
<h1>{{ msg }}</h1>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: String
}
}
</script>
父组件
<template>
<div id="app">
<HelloWorld msg="hello world" />
</div>
</template>
<script>
export default {
name: "App",
components: {
HelloWorld,
},
};
</script>
动态传递字符串
子组件
<tenplate>
<div>
<h1>{{ msg }}</h1>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: String
}
}
</script>
父组件
<template>
<div id="app">
<HelloWorld :msg="hello" />
</div>
</template>
<script>
export default {
name: "App",
components: {
HelloWorld,
},
data() {
return {
hello: "hello world",
};
},
};
</script>
动态传递数组
子组件
<template>
<div class="hello">
<ul>
<li v-for="item in hellos" :key="item">{{ item }}</li>
</ul>
<h1>{{ msg }}</h1>
</div>
</template>
<script>
export default {
name: "HelloWorld",
props: {
hellos: String,
msg: String
},
};
</script>
父组件
<template>
<div id="app">
<HelloWorld :msg="hello" :hellos="hellos" />
</div>
</template>
export default {
name: "App",
components: {
HelloWorld,
},
data() {
return {
hello: "hello world",
hellos: ["111", "222", "333"],
};
},
};
</script>
动态传递对象
子组件
<template>
<div class="hello">
<h1>{{ msg.id }}</h1>
<h2>{{ msg.name }}</h2>
</div>
</template>
<script>
export default {
name: "HelloWorld",
props: {
msg: Object,
},
};
</script>
父组件
<template>
<div id="app">
<HelloWorld :msg="hello"/>
</div>
</template>
<script>
export default {
name: "App",
components: {
HelloWorld,
},
data() {
return {
hello: {
id: 1,
name: "wecle",
},
};
},
};
</script>
prop验证
type可以是:
String
Number
Boolean
Array
Object
Date
Funtion
Symbol
子组件
<template>
<div class="hello">
<h1>{{ string }}</h1>
<h1>{{ number }}</h1>
<h1>{{ boolean }}</h1>
<h1>{{ array }}</h1>
<h1>{{ object }}</h1>
</div>
</template>
<script>
export default {
name: "HelloWorld",
props: {
string: {
type: String,
},
number: {
type: Number,
},
boolean: {
type: Boolean,
},
array: {
type: Array,
},
object: {
type: Object,
},
},
};
</script>
父组件
<template>
<div id="app">
<HelloWorld
:string="string"
:number="number"
:boolean="boolean"
:array="array"
:object="object"
/>
</div>
</template>
<script>
export default {
name: "App",
components: {
HelloWorld,
},
data() {
return {
string: "验证字符串",
number: 123456,
boolean: true,
array: ["这是", "一个", "数组"],
object: {
id: 1,
name: "验证对象",
},
};
},
};
</script>