1. 子组件的使用
Vue中
- 编写子组件
- 在需要使用的父组件中通过import引入
- 在vue的components中注册
- 在模板中使用
//子组件 bar.vue
<template>
<div class="search-box">
<div @click="say" :title="title" class="icon-dismiss"></div>
</div>
</template>
<script>
export default{
props:{
title:{
type:String,
default:''
}
}
},
methods:{
say(){
console.log('明天不上班');
this.$emit('helloWorld')
}
}
</script>
// 父组件 foo.vue
<template>
<div class="container">
<bar :title="title" @helloWorld="helloWorld"></bar>
</div>
</template>
<script>
import Bar from './bar.vue'
export default{
data(){
return{
title:"我是标题"
}
},
methods:{
helloWorld(){
console.log('我接收到子组件传递的事件了')
}
},
components:{
Bar
}
</script>
小程序中
- 编写子组件
- 在子组件的json文件中,将该文件声明为组件
{
"component": true
}
- 在需要引入的父组件的json文件中,在usingComponents填写引入组件的组件名以及路径
"usingComponents": {
"tab-bar": "../../components/tabBar/tabBar"
}
- 在父组件中,直接引入即可
<tab-bar currentpage="index"></tab-bar>
具体代码
// 子组件
<!--components/tabBar/tabBar.wxml-->
<view class='tabbar-wrapper'>
<view class='left-bar {{currentpage==="index"?"active":""}}' bindtap='jumpToIndex'>
<text class='iconfont icon-shouye'></text>
<view>首页</view>
</view>
<view class='right-bar {{currentpage==="setting"?"active":""}}' bindtap='jumpToSetting'>
<text class='iconfont icon-shezhi'></text>
<view>设置</view>
</view>
</view>
2. 父子组件通信
vue中
父组件向子组件传递数据,只需要在子组件通过v-bind传入一个值,在子组件中,通过props接收,即可完成数据的传递
// 父组件 foo.vue
<template>
<div class="container">
<bar :title="title"></bar>
</div>
</template>
<script>
import Bar from './bar.vue'
export default{
data(){
return{
title:"我是标题"
}
},
components:{
Bar
}
</script>
// 子组件bar.vue
<template>
<div class="search-box">
<div :title="title" ></div>
</div>
</template>
<script>
export default{
props:{
title:{
type:String,
default:''
}
}
}
</script>
子组件和父组件通信可以通过this.$emit将方法和数据传递给父组件
小程序中
父组件向子组件通信和vue类似,但是小程序没有通过v-bind,而是直接将值赋值给一个变量,如下:
<tab-bar currentpage="index"></tab-bar>
此处, “index”就是要向子组件传递的值
在子组件properties中,接收传递的值
properties: {
// 弹窗标题
currentpage: { // 属性名
type: String, // 类型(必填),目前接受的类型包括:String, Number, Boolean, Object, Array, null(表示任意类型)
value: 'index' // 属性初始值(可选),如果未指定则会根据类型选择一个
}
}
子组件向父组件通信和vue也很类似,代码如下:
//子组件中
methods: {
// 传递给父组件
cancelBut: function (e) {
var that = this;
var myEventDetail = { pickerShow: false, type: 'cancel' } // detail对象,提供给事件监听函数
this.triggerEvent('myevent', myEventDetail) //myevent自定义名称事件,父组件中使用
},
}
//父组件中
<bar bind:myevent="toggleToast"></bar>
// 获取子组件信息
toggleToast(e){
console.log(e.detail)
}
3.如果父组件想要调用子组件的方法
vue会给子组件添加一个ref属性,通过this.$refs.ref的值便可以获取到该子组件,然后便可以调用子组件中的任意方法,例如
//子组件
<bar ref="bar"></bar>
//父组件
this.$ref.bar.子组件的方法
小程序是给子组件添加id或者class,然后通过this.selectComponent找到子组件,然后再调用子组件的方法,示例:
//子组件
<bar id="bar"></bar>
// 父组件
this.selectComponent('#id').syaHello()
网友评论