1. 父传子
(如果父组件声明了,子组件没有,可以通过$attr属性来获取
//父组件 <child :text="传递的值"/> //子组件child // 第一种方式 $attr.name <div>{{ $attr.title }}</div> //第二种方式 props props:["title"] methods:{ show(){ console.log(this.title)} }
props:{ title:{ type:String, //必传约束 required:true, default:'123' } }
//main.js中定义全局组件 Vue.component('name',引入的组件) <name/>
注意 : 子组件单标签不支持传数据
2.子传父组件 使用自定义事件。父组件触发子事件
//子组件传入的值 <button @click="post()">传值</button> post(){ this.$emit('Eventname','传入的值') } //父组件传入的值 <child @Eventname="getData"/> getData(data){ console.log(data) )
1)单向数据流,思想一般支持父组件
2)给自组件绑定一个事件,绑定父组件回调函数
3)子组件通过this.$emit(事件,值)触发父组件的
。 可以作为子改父的方式
。 核心是通知父组件自己改
3.slot插槽 父传子 传值
基础用法:
<child> //v-slot只能写在template上 <template v-slot:header>传递给子组件的头部header </template> <button>传递给子组件的插槽</button> <button #footer>传递给子组件的footer插槽</button> </child> <template> <div> // 默认填充 <slot> </slot> <slot name="header"> </slot> <slot name="footer"> </slot> </div> </template>
父组件 也可以回传给子组件 将数据放在子组件插槽中
子组件
<template> <div> <div class="box" v-for="({h,d,f},index) in dataArr" :key="index"> <!-- <slot/> 默认被填充 --> <slot :h="h" name="header"></slot> <br /> <slot :d="d" name="default"></slot> <br /> <slot :f="f" name="footer" /> </div> </div> </template> <script> export default { props: ["dataArr"] }; </script>
父组件中
<SonC :dataArr="arr"> <template v-slot:header="{ h }"> <button>传递给子组件的头部插槽 => {{h}}</button> </template> <!-- v-slot只能卸载template或者组件上 --> <template #default="{d}"> <button >传递给子组件的插槽 => {{d}}</button> </template> <template #footer="{f}"> <button>传递给子组件的底部插槽 => {{f}}</button> </template> </SonC>
data() { return { text: "变量传递", arr: [ { h: "头部标题1", d: "中间标题1", f: "底部头部标题1" }, { h: "头部标题2", d: "中间标题2", f: "底部头部标题2" } ] }; },
总结:
1 )编写UI界面,大体风格一致,自定义头部内容
2 )作用域插槽回传:考虑到用户开发v-for方法不方便,
子组件内容封装对数据的解析回传值使用