传静态的属性
子组件:
<template>
<div>
<h1>{{ msg }}</h1> </div> </template> <script> export default { props: ["msg"] } </script>
父组件:
<template>
<div id="app"> <HelloWorld msg="hello"/> </div> </template> <script> import HelloWorld from "./components/HelloWorld.vue"; export default { components: { HelloWorld } }; </script>
好了,这样就完成了一个最简单的使用prop接收父元素的值
传动态字符串
子组件
<template>
<div>
<h1>{{ msg }}</h1> </div> </template> <script> export default { props: ["msg"] } </script>
父组件
<template>
<div id="app"> <HelloWorld :msg="hello"/> </div> </template> <script> import HelloWorld from "./components/HelloWorld.vue"; export default { components: { HelloWorld }, data() { return { hello: "hello world" } } }; </script>
可以看到,子组件我未做任何修改,只是在父组件做了一些修改
传动态数组
子组件
<template>
<div>
<ul> <li v-for="item in msg" :key="item"> {{ item }} </li> </ul> </div> </template> <script> export default { props: ["msg"] } </script>
父组件
<template>
<div id="app"> <HelloWorld :msg="hello"/> </div> </template> <script> import HelloWorld from "./components/HelloWorld.vue"; export default { components: { HelloWorld }, data() { return { hello: ["aa", "bb", "cc"] } } }; </script>
传动态对象
子组件
<template>
<div>
<h1>{{ msg.id }}</h1> <h2>{{ msg.name }}</h2> </div> </template> <script> export default { props: ["msg"] } </script>
父组件
<template>
<div id="app"> <HelloWorld :msg="hello"/> </div> </template> <script> import HelloWorld from "./components/HelloWorld.vue"; export default { components: { HelloWorld }, data() { return { hello: { id: 1, name: "hello dj" } } } }; </script>
对prop的状态进行验证
prop的状态可以为
- String
- Number
- Boolean
- Array
- Object
- Date
- Function
- Symbol
下面进行演示
子组件
<template>
<div>
<h1>{{ num }}</h1> <h1>{{ msg }}</h1> <h1>{{ obj.id }}</h1> <h2>{{ obj.name }}</h2> <ul> <li v-for="item in arrs" :key="item"> {{ item }} </li> </ul> </div> </template> <script> export default { props: { num: { type: Number }, msg: { type: String }, arrs: { type: Array }, obj: { type: Object } } } </script>
父组件
<template>
<div id="app"> <HelloWorld :num="num" :msg="hello" :arrs="arr" :obj="post"/> </div> </template> <script> import HelloWorld from "./components/HelloWorld.vue"; export default { components: { HelloWorld }, data() { return { num: 10, hello: "hello world", arr: ["aa","bb","cc"], post: { id: 1, name: "hello dj" } } } }; </script>
上面演示了Number,String,Array,object的用法
作者:回不去的那些时光
链接:https://www.jianshu.com/p/bdda44c00443
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。