常规使用
父组件
<style lang="scss"> </style> <template> <xx></xx> </template> <script> import wepy from "wepy"; import { shttp } from "../utils/http"; import xx from "../../components/xx/xx";//import导入 export default class Home extends wepy.page { config = { navigationBarTitleText: "首页", "usingComponents": { "van-dialog": "../components/vant/dialog/index", }, }; data = {}; components = { xx,//声明组件 }; events = { 子组件传入的方法名(e){ //e为子组件传入的值 } } computed = {}//监听数据变化 onLoad(options) {} onShow(){} } </script>
子组件(只有onLoad生命周期)
<style lang="scss"> </style> <template> </template> <script> import wepy from "wepy"; import {shttp} from "../../utils/http"; export default class goodsDetails extends wepy.component { props = {}//接收父组件的传值 data = {}//组件局部变量 watch = {}//监听数据变化 onLoad(){}//监听组件初始化 //组件内部方法 methods = { 方法名(){ this.$emit("父组件接收的方法名",需要传入的某个值) } } } </script>
1.父传子
父组件传值:用.sync进行修饰动态传值(静态传值只能传字符串,接收的时候用String类型)
动态传值
<panel :num.sync="num" customFn.user="customEvent"></panel>
静态传值(意思就是父组件值改变的时候子组件不会同步修改)
<panel name="ddddd"></panel>
子组件接收值
props = { num: { type: Number,//类型 value:1,//默认值 }, };
2.子向父传值
this.$emit("changNum",num);
3.父元素接收值并进行改变
events = { changNum(e){ this.num = e; } }
4.插槽
说明:子组件定义slot,然后父组件直接显示了,你不用的时候得定义一个空的
子组件
<style lang="scss"> </style> <template> <view class="panel"> <slot name="title">默认标题</slot> <slot name="content">默认内容</slot> </view> </template> <script> import wepy from "wepy"; export default class test extends wepy.component { props = { showSuccess:{ type:Boolean, value:false, }, bigTitle:{ type: Array, value: [], }, smallTitle:{ type: Array, value: [], }, }; data = {}; components = {}; watch = { } onLoad(){ this.cloudUrl = this.$parent.globalData.cloudUrl; } onShow(){} methods = { }; } </script>
父组件
<panel> <view slot="title">我修改了默认标题</view> </panel>