15 uni组件的创建及组件的生命周期
组件的创建
1、项目目录下新建components文件夹,创建组件bread.vue,写入内容
<template> <view id="myBread"> bread组件{{info}} </view> </template>
<script> export default { data() { return { info:"hello bread", timer:null, }; }, beforeCreate(){ console.log("创建前",this.info); }, created() { console.log("创建完成",this.info); this.timer = setInterval(()=>{ console.log("定时器执行中"); },5000) }, beforeMount(){ console.log("挂载前"); }, mounted() { console.log("挂载完成"); }, destroyed(){ console.log("组件销毁"); clearInterval(this.timer); console.log("清除定时器"); } } </script>
2、引入bread.vue组件 => 注册组件components =>在页面中使用
<template> <view class="content"> <bread v-if="flag"></bread> <button type="primary" @click="showBread">是否显示flag组件</button> </view> </template>
<script> import bread from "../../components/bread.vue" //引入组件 export default { components:{ bread, //注册组件 }, data:{ flag:true, }, methods:{ showBread(){ this.flag = !this.flag; //控制组件的显示与隐藏 console.log(this.flag); } } } </script>

浙公网安备 33010602011771号