components : “helloComp”
<!-- 总结组件步骤
1.创建组件页面
2.引入组件 import 组件名 form 路径
3.在引入页面components 中注册 组件名
4.使用组件名即可使用
5.组件动态传值只需更换list数组进行循环输出
-->
<!-- 定义组件名为helloComp -->
<template name="helloComp">
<view>
<block v-for="(item,index) in myval" :key="index">
<view class="mesg">
<text>{{item.id}}</text>
<text @click="handleClick">{{item.text}}</text>
</view>
</block>
</view>
<!-- </view> -->
</template>
<script>
export default {
// 定义组件名为helloComp,
name: "helloComp",
data() {
return {
msg: 'nihao'
}
},
methods: {
//子传父 传递数据 通过事件触发
handleClick () {
console.log('来自子组件的数据')
//两个参数 自定义事件名称 要传递的参数
this.$emit("textChange",e.timeStamp)
}
},
//定义组件内部使用的属性
props: ["myval"]
}
</script>
<style>
.txt {
color: red;
}
</style>
页面引用
<template>
<view class="page">
<!-- 使用自定义标签 -->
<helloComp :myval='list'></helloComp>
<view >
子组件传来的{{text}}
</view>
<view v-for="item in list">
{{item.id}} -- {{item.text}}
</view>
</view>
</template>
<script>
//导入自定义组件
import helloComp from "../../components/helloComp.vue";
export default {
data() {
return {
list : [
{
id : 0,
text : "苹果"
},
{
id : 1,
text : "草莓"
}
],
text : ""
}
},
method : {
//接收组附件的自定义事件
textChange (e) {
console.log('父组件的自定义事件被触发')
console.log(e)
this.text = e;
}
},
components: {
// 注册自定义组件
helloComp
}
}
</script>
<style>
</style>