Vue属性、生命周期、过滤器

本文详细介绍了Vue.js中computed计算属性的使用规则,以及watch监听属性的监听机制,包括简写和深度监听。同时对比了两者之间的区别,并通过示例展示了在实际项目中的应用,以及生命周期函数和过滤器的运用。
摘要由CSDN通过智能技术生成

Vue属性

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:{
            obj:{
                immediate:false,
                deep:true,
                handler(newVlaue,oldValue){
                    console.log("--------obj-------");
                    console.log(newVlaue);
                    console.log(oldValue);
                }
            },
            bool:{
                immediate:true,
                handler(newVlaue,oldValue){
                    console.log(newVlaue);
                    console.log(oldValue);
                    if(newVlaue==true){
                        this.userName = "张三";
                        this.obj.id = 100;
                    }else{
                        this.userName = "李四";
                        this.obj.id = 99;
                    }
                }
            },
            str(newVlaue,oldValue){
                console.log(newVlaue);
                console.log(oldValue);
                console.log(this);
            }
        },

computed计算和watch监听属性的区别

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

综合案例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <div>
            <h1>今天的天气{{str}}</h1>
            <h2>{{userName}}</h2>
            <h3>{{obj.id}}</h3>
            <button @click="func()">点击切换天气</button>
        </div>
    </div>
</body>
<script src="./vue.js"></script>
<script>
    Vue.config.productionTip = false;
    var vm = new Vue({
        el:"#app",
        data() {
            return {
                bool:true,
                userName:"",
                obj:{
                    id:99,
                }
            }
        },
        methods: {
            func(){
                this.bool = !this.bool;
            }
        },
        computed:{
            str(){
                return this.bool?"炎热":"凉爽"
            }
        },
        watch:{
            obj:{
                immediate:false,
                deep:true,
                handler(newVlaue,oldValue){
                    console.log("--------obj-------");
                    console.log(newVlaue);
                    console.log(oldValue);
                }
            },
            bool:{
                immediate:true,
                handler(newVlaue,oldValue){
                    console.log(newVlaue);
                    console.log(oldValue);
                    if(newVlaue==true){
                        this.userName = "张三";
                        this.obj.id = 100;
                    }else{
                        this.userName = "李四";
                        this.obj.id = 99;
                    }
                }
            },
            str(newVlaue,oldValue){
                console.log(newVlaue);
                console.log(oldValue);
                console.log(this);
            }
        },
        directives:{

        }
    })
    // vm.$watch("userName",{
    //     immediate:false,
    //     handler(newVlaue,oldValue){
    //         console.log("--------userName---------");
    //         console.log(newVlaue);
    //         console.log(oldValue);
    //         console.log(this);
    //     }
    // })
    vm.$watch("userName",function(newVlaue,oldValue){
            console.log("--------userName---------");
            console.log(newVlaue);
            console.log(oldValue);
            console.log(this);
            console.log(this.bool);
    })
</script>
</html>

生命周期

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

八大生命周期

beforeCreate初始化之前,不能获取data中的数据

beforeCreate() {
            // console.log(this.userName);
            // console.log(this.sum());
        },

created初始化之后,获取data中的数据

created() {
            // console.log(this.userName);
            // console.log(this.sum());
        },

beforeMount解析前|挂载前


>  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更新前

beforeUpdate() {
            // setTimeout(()=>{
            //     this.userName = "李四";
            // },1000)
        },

updated更新后(常用)

 updated() {
            // this.userName = "王五";
        },

beforeDestroy销毁前

>    beforeDestroy() {
>             clearInterval(this.timeValue);
>             console.log("触发了销毁前");
>         },

destroyed销毁后(常用)

destroyed() {
            console.log("触发了销毁后");
        },
八大生命周期综合案例:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <h1>{{time}}</h1>
        <h1>{{time|times}}</h1>
        <h1>{{time|times|myTime}}</h1>
        <h1 v-show="bool" class="box">{{userName}}</h1>
        <button @click="func()">点击</button>
        <hr>
        <h1 :style="{opacity}">我是测试文本</h1>
        <button @click="opacity=1">点击显示</button>
        <button @click="stop()">停止</button>
    </div>
</body>
<script src="../vue.js"></script>
<!-- <script src="https://cdn.bootcdn.net/ajax/libs/dayjs/1.10.6/dayjs.min.js"></script> -->
<script>
    Vue.config.productionTip = false;
    // 生命周期
    // 1.生命周期函数,钩子函数
    // 2.生命周期函数命名不能修改
    // 3.this指向Vue实例(vm)
    // ----------------------
    Vue.filter("myTime",function(value){
        // console.log(value);
        // return value.slice(0,11);
        // return value.substring(0,11);
        return value.substr(0,11);
    })
    var vm = new Vue({
        el:"#app",
        data() {
            return {
                time:Date.now(),
                userName:"张三",
                bool:true,
                // opacity:"opacity:1",
                opacity:1,
                timeValue:"",
            }
        },
        methods: {
            sum(){
                return 100;
            },
            func(){
                this.userName = "9999"
            },
            stop(){
                this.$destroy();
            }
        },
        // beforeCreate初始化之前,不能获取data中的数据
        beforeCreate() {
            // console.log(this.userName);
            // console.log(this.sum());
        },
        // created初始化之后,获取data中的数据
        created() {
            // console.log(this.userName);
            // console.log(this.sum());
        },
        // beforeMount解析前|挂载前
        beforeMount() {
            // this.bool = false;
            // document.getElementsByClassName("box")[0].style.color = "red";
        },
        // mounted解析后|挂载后
        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更新前
        beforeUpdate() {
            // setTimeout(()=>{
            //     this.userName = "李四";
            // },1000)
        },
        // updated更新后
        updated() {
            // this.userName = "王五";
        },
        // beforeDestroy销毁前
        beforeDestroy() {
            clearInterval(this.timeValue);
            console.log("触发了销毁前");
        },
        // destroyed销毁后
        destroyed() {
            console.log("触发了销毁后");
        },
    })
</script>
</html>

过滤器

定义:对要显示的的数据进行特定的格式化后再显示

1.局部过滤器new Vue({filters:{名称(value){}}}),
全局过滤器Vue.filter(“名称”,function(value){})
2.返回一个新的数据
3.使用时|名称, 多个过滤器串联,拿取的值是前一个

过滤器综合案例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <h1>{{time}}</h1>
        <h1>{{time|times}}</h1>
        <h1>{{time|times|myTime}}</h1>
        <h1 v-show="bool" class="box">{{userName}}</h1>
        <button @click="func()">点击</button>
        <hr>
        <h1 :style="{opacity}">我是测试文本</h1>
        <button @click="opacity=1">点击显示</button>
        <button @click="stop()">停止</button>
    </div>
</body>
<script src="../vue.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/dayjs/1.10.6/dayjs.min.js"></script>
<script>
    Vue.config.productionTip = false;
    Vue.filter("myTime",function(value){
        // console.log(value);
        // return value.slice(0,11);
        // return value.substring(0,11);
        return value.substr(0,11);
    })
    var vm = new Vue({
        el:"#app",
        data() {
            return {
                time:Date.now(),
                userName:"张三",
                bool:true,
                // opacity:"opacity:1",
                opacity:1,
                timeValue:"",
            }
        },
        methods: {
           
        },
       
        // 局部过滤器
        filters:{
            times(value,str="YYYY年MM月DD日 HH:mm:ss"){
                // console.log(value);
                return dayjs(value).format(str);
                // return new Date(value);
                // let a = new Date(value);
                // return a.toISOString();
                // let day = parseInt(value/1000/60/60/24);
                // let days = day;
                // let year = 1970;
                // while (day>=366) {
                //     if(year%4==0){
                //         day-=366;
                //     }else{
                //         day-=365;
                //     }
                //     year+=1;
                // }
                // let month = 1;
                // while(day>=28){
                //     if(month==1||month==3||month==5||month==7||month==8||month==10||month==12){
                //         if(day<31){
                //             break;
                //         }
                //         day-=31;
                //     }else if(month==4||month==6||month==9||month==11){
                //         if(day<30){
                //             break;
                //         }
                //         day-=30;
                //     }else if(month==2&&year%4==0){
                //         if(day<29){
                //             break;
                //         }
                //         day-=29;
                //     }else{
                //         if(day<28){
                //             break;
                //         }
                //         day-=28;
                //     }
                //     month+=1;
                // }
                // console.log(year+"年"+month+"月"+(day+1)+"日");
            }
        }
    })
    console.log(vm);
</script>
</html>
  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值