【 Vue.js 属性 | 生命周期 】

本文详细介绍了Vue.js中computed计算属性的使用规则、watch监听属性的区别,以及组件的生命周期函数,包括beforeCreate、created、beforeMount等,同时涵盖局部和全局过滤器的用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

computed计算属性

规则:
1.用已有的属性计算不存在的属性
2.默认调用一次get()
3.简写时注意:
只有值不发生改变才可以是用简写(函数),值发生改变必须使用对象,才可以配置set()方法
4.底层原理使用
Object.definproperty(目标对象,键名,{get(){},set(value){}})

	
	computed:{
            str(){
                return this.bool?"炎热":"凉爽"
            }
        },
        
        来回切换输入 :炎热/凉爽
        

watch监听属性___时时监听

规则:
1.监听已存在的属性
2.immediate:true默认调用一次,false不会
3.简写:只有handler方法才可以简写。写法:监听的属性(新值,旧值){}
4.监听对象中的值需要深度监听,deep:true

watch监听属性_computed计算属性 区别:

1.computed能做的watch都可以做,watch可以做的,computed不一定能做
2.使用vm.$watch方法时,需要使用普通函数
3.对于定时器,函数回调,ajax回调,promise回调,建议使用箭头函数

  • 代码演示:
 		
        // 计算属性
        computed:{

        },
        // 监听属性
        watch:{

        },
        

生命周期

1.生命周期函数,钩子函数
2.生命周期函数命名不能修改
3.this指向Vue实例(vm)

生命周期中属性:

beforeCreate初始化之前,不能获取data中的数据
created初始化之后,获取data中的数据
   beforeCreate() {
            console.log(this.userName);
            console.log(this.sum());
        },
 created() {
            console.log(this.userName);
            console.log(this.sum());
        },
beforeMount解析前/挂载前
mounted解析后/挂载后
 beforeMount() {
            this.bool = false;
            document.getElementsByClassName("box")[0].style.color = "red";
        },
 mounted() {
            this.userName = "王五";
            document.getElementsByClassName("box")[0].style.color = "red";
            this.timeValue = setInterval(()=>{
                this.opacity-=0.01;
                if(this.opacity<=0){
                    this.opacity=1;
                }
            },10)
        },
beforeUpdate更新前
updated更新后
 beforeUpdate() {
         setTimeout(()=>{
             this.userName = "李四";
         },1000)
    },
  updated() {
         this.userName = "王五";
    },
beforeDestroy销毁前
destroyed销毁后
beforeDestroy() {
    clearInterval(this.timeValue);
    console.log("触发了销毁前");
},
destroyed() {
        console.log("触发了销毁后");
    },

filters过滤器分两种:

1.局部过滤器
写法:new Vue ( { filters:{名称 ( value ){} }}),
2.全局过滤器
写法:Vue.filter ( "名称 " , function ( value ){})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值