父传子值
可以在父组件使用中增加:命名,子组件中通过props:["命名"] 接收的方式进行处理。
支持多种类型,当然也支持传对象、函数、HTML内容(后面讲的插槽),也可以通过provide进行跨级透传
props逐级传参示例
示例
父组件(容器) app.vue
<!--内容控制-->
<template>传值<test :num="100" :names="names" :msg="msg"/>
</template>
<!--JS 控制-->
<script>import test from "@/components/test.vue";export default {components: {test},data() {return {msg: '测试一下',names:["张三","李四","王五"],user:{name:'张三',age:18}}}}</script>
子组件 test.vue
<template><p>接收到: {{msg}}</p><p>{{num}}</p><p v-for="(item,index) in names" :key="index">{{item}}</p>
</template><script >export default {props:["msg","num","names"]}
</script>
有时我们需要给传的值类型进行约束,在接收时可以进行配置
子组件 test.vue
<template><p>接收到: {{msg}}</p><p>{{num}}</p><p v-for="(item,index) in names" :key="index">{{item}}</p>
</template><script >export default {props: {msg: {type: String,default: 'hello world'},num: {type: Number,default: 0},names: {type: Array,default: () => {return ['1','2','3']}}}}
</script>
provide、inject透传示例
试想一下,A下面有子组件B,而B组件下又有C组件,C组件下又有D组件;如果使用Props传的话太麻烦了,所以就有了透传。
父 app.vue
<!--内容控制-->
<template><A></A></template>
<!--JS 控制-->
<script>import A from "@/components/A.vue";export default {components: {A},data() {return {name: '李四',age: 100,act: "test2"}},provide() {return {name: this.name,age: this.age,act: this.act}}}
</script>
子A.vue
<template><B></B>
</template><script>
import B from "@/components/B.vue"
export default {components: {B}
}</script>
孙B.vue
<template><p>{{name}}</p><p>{{PName}}</p>
</template><script>
export default {data() {return {PName: this.name,age: this.age,act: this.act}},inject: ['name', 'age', 'act'],
}</script>
子传父值
在实际应用中我们需要把子组件的操作反馈给父组件进行响应,例如 列表中通过点击新增调出子组件新增功能,当子组件新增完成后需要对父组件的内容刷新,否则的话就不是一个完整的功能页面。
具体做法就是在子组件上通过自定义事件(自定义函数)的this.$emit(父组件函数名,传的值)进行实现,也可以通过props 通过传函数,子组件定义接收类型为函数的方式实现父传子。
this.$emit 示例
父组件 App.vue
<!--内容控制-->
<template><p>子组件传过来的数据</p><test @getData="getData"></test><p>{{name}}</p><p>{{age}}</p>
</template>
<!--JS 控制-->
<script>import test from "@/components/test.vue";export default {components: {test},data() {return {name: '李四',age: 100}},methods: {getData(data) {this.name = data.name;this.age = data.age;}}}
</script>
子组件 test.vue
<template><button @click="sendData">传递数据到父组件</button>
</template><script >export default {methods:{sendData(){this.$emit('getData',{name:'张三',age:18})}}}
</script>
Props 传函数实现
父组件 App.vue
<!--内容控制-->
<template><test :name="name" :age="age" :OnFunction="getData"></test><p>子组件传过来的数据</p><p>{{name}}</p><p>{{age}}</p>
</template>
<!--JS 控制-->
<script>import test from "@/components/test.vue";export default {components: {test},data() {return {name: '李四',age: 100}},methods: {getData(data) {this.name = data.name;this.age = data.age;}}}
</script>
子组件 test.vue
<template><div><p>测试子组件</p><div>姓名:{{name}}</div><div>年龄:{{age}}</div></div><button @click="OnFunction({name:'王五',age:99})">传递数据</button>
</template><script >export default {props:{ name:String,age:Number,OnFunction:Function }}
</script>