Vue 组件代码解析:空调控制组件示例
这是一个 Vue 组件的代码,用于控制空调的开关、温度和模式。
<script>
import { toRefs } from 'vue';
export default {
components: {},
data() {
// 这里存放数据
return {
info: JSON.parse(JSON.stringify(this.modalInfo)),
};
},
props: {
modalInfo: {
type: Object,
default: () => {}
}
},
watch: {
modalInfo() {
this.info = JSON.parse(JSON.stringify(this.modalInfo))
}
},
// 监听属性 类似于data概念
computed: {},
// 方法集合
methods: {
onOpen() {
this.info.status = this.info.status == 'open' ? 'close' : 'open'
this.$emit('changeInfo', this.info)
},
onUp() {
if(this.info.status == 'close') return ;
if(this.info.temperature==30) return ;
this.info.temperature++
this.$emit('changeInfo', this.info)
},
onDown() {
if(this.info.status == 'close') return ;
if(this.info.temperature==16) return ;
this.info.temperature--
this.$emit('changeInfo', this.info)
},
onSun() {
if(this.info.status == 'close') return ;
this.info.model = 'hot'
this.$emit('changeInfo', this.info)
},
onSnow() {
if(this.info.status == 'close') return ;
this.info.model = 'cold'
this.$emit('changeInfo', this.info)
},
},
// 生命周期 - 创建完成(可以访问当前this实例)
created() {
},
// 生命周期 - 挂载完成(可以访问DOM元素)
mounted() {
// this.info =
},
beforeCreate() {}, //生命周期 - 创建之前
beforeMount() {}, //生命周期 - 挂载之前
beforeUpdate() {}, //生命周期 - 更新之前
updated() {}, //生命周期 - 更新之后
beforeDestroy() {}, //生命周期 - 销毁之前
destroyed() {}, //生命周期 - 销毁完成
}
</script>
代码解析
components: 组件中包含的子组件,这里为空。data: 组件中存放的数据,包含一个info对象,该对象通过JSON.parse和JSON.stringify方法对传入的modalInfo对象进行深拷贝得到。props: 组件的属性,包含一个modalInfo对象,类型为Object,默认值为空对象。watch: 组件的属性监听器,当modalInfo对象发生变化时,将其深拷贝得到的值赋给info对象。computed: 组件的计算属性,这里为空。methods: 组件的方法集合,包含onOpen、onUp、onDown、onSun、onSnow方法,分别用于控制空调的开关、温度加减、模式切换。created: 组件的created生命周期钩子函数,此时可以访问当前实例。mounted: 组件的mounted生命周期钩子函数,此时可以访问 DOM 元素。beforeCreate、beforeMount、beforeUpdate、updated、beforeDestroy、destroyed: 组件的其他生命周期钩子函数。
代码说明
- 使用
toRefs方法可以将传入的modalInfo对象转换为响应式数据,这样当modalInfo发生变化时,info对象也会同步更新。 - 通过
watch方法监听modalInfo的变化,并在变化时更新info对象。 methods中的各个方法用于控制空调的开关、温度和模式,并通过this.$emit方法将info对象的变化传递给父组件。
该示例代码展示了一个简单的 Vue 组件,用于控制空调的开关、温度和模式。可以根据实际需求进行扩展和修改。
希望以上内容对您有所帮助。如果您还有其他问题,请随时提出。
原文地址: https://www.cveoy.top/t/topic/kHei 著作权归作者所有。请勿转载和采集!