vue-计算属性、监听属性、生命周期钩子函数

发布时间 2023-09-19 17:04:12作者: Maverick-Lucky

计算属性

1. 计算属性是基于他们的依赖变量进行缓存的

2. 计算属性只有在它相关依赖变量发生改变时才会重新求值,否则不会变(函数只要页面变化,就会重新运算)

3. 计算属性就像python中的property,可以把方法/函数伪装成属性

4. 计算属性,必须有返回值

 实现输入input中后名字首字母大写

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./js/vue.js"></script>
</head>
<body>
<div id="app">
    <h5>实现输入input中后名字首字母大写</h5>
<!--    substring:截取字符串,substring(0,1):截取第一位-->
<!--    <input type="text" v-model="username"> -&#45;&#45;&#45;&#45;&#45;&#45;&ndash;&gt;{{username.substring(0,1).toUpperCase()+username.substring(1)}}-->
    <input type="text" v-model="username"> ---->{{getUpdate()}}
    <br>
    <input type="text" v-model="age"> ---->{{age}}
    <h5>通过计算属性来实现 ---》函数当属性用</h5>
    <input type="text" v-model="name">---->{{getBig}}

</div>
</body>
<script>
    var vm=new Vue({
        el:'#app',
        data:{
            username:'',
            age:'',
            name:''
        },
        methods:{
            getUpdate(){
                console.log('函数执行了')
                // 截取字符串的第一个字符,将它转换成大写
                return this.username.substring(0,1).toUpperCase()+this.username.substring(1)
            }
        },
        // 计算属性
        computed :{
            getBig(){
                console.log('计算属性执行了')
                // 截取字符串的第一个字符,将它转换成大写
                return this.name.substring(0,1).toUpperCase()+this.name.substring(1)
            }
        }
    })
</script>
</html>

 

结果:

对于函数来说只要页面变化,就会重新计算

对于计算属性来说,可以将函数/方法伪装成属性来使用

 重写过滤案例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.js"></script>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <script src="./js/vue.js"></script>
</head>
<body>
<div id="app">
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-6 col-md-offset-3">
                <div class="text-center">
                    <h5>数组过滤案例</h5>
                    <input type="text" v-model="myText">
                    <hr>
                    <!--newList:就是下面所写的计算属性,当属性用-->
                    <p v-for="item in newList">{{item}}</p>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
<script>
    let vm = new Vue({
        el: '#app',
        data: {
            myText: '',
            datalist: ['a', 'at', 'atom', 'be', 'beyond', 'cs', 'csrf', 'e', 'egg', 'eabc'],
            newlist: ['a', 'at', 'atom', 'be', 'beyond', 'cs', 'csrf', 'e', 'egg', 'eabc'],
        },
        computed:{
            //写一个计算属性
            newList(){
                // 只要myText发生变化,newList就会发生变化
                return this.datalist.filter(item =>item.indexOf(this.myText) >= 0)
            }
        }
    })

</script>
</html>

 

结果:

计算属性只有在它相关依赖变量发生改变时才会重新求值,否则不会变

监听(侦听)属性

属性如果发生变化,就会执行某个函数

监听属性是没有返回值的

使用:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/vue.js"></script>
</head>
<body>
<div id="app">
    <h5>监听属性的使用</h5>
    <input type="text" v-model="username"> ---> {{username}}
</div>
</body>
<script>
    var vm=new Vue({
        el:'#app',
        data:{
            username:''
        },
        watch:{
            // 当username发生变化,监听属性就会发生变化
            username(newValue,oldValue){
                console.log('老值',oldValue)
                console.log('新值',newValue)
                console.log('监听属性执行了')
            }
        }
    })
</script>
</html>

结果:

 

Vue生命周期

new Vue() ----》Vue被创建出来 ----》页面关闭 ----》Vue被销毁掉 :

  这个整个经历了一整个周期 ----》Vue帮我们提供了一些钩子函数(钩子函数:写了就会执行,不写就不会执行),到某个阶段就会触发某个函数的执行

 

一共有8个生命周期钩子函数:

beforeCreate:  创建Vue实例之前调用

created:      创建Vue实例成功后调用

beforeMount:   渲染DOM之前调用

mounted:    渲染DOM之后调用

beforeUpdate:  重新渲染(刷新页面)之前调用(数据更新等操作时,控制DOM重新渲染)

updated:      重新渲染完成之后调用

beforeDestory:    销毁之前调用

destroyed:    销毁之前调用

 

 

每个组件也有这个8个生命周期钩子

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/vue.js"></script>
</head>
<body>
<div id="app">
    <h5>生命周期钩子</h5>
    <input type="text" v-model="username">---->{{username}}
    <h5>使用组件</h5>
    <button @click="handleShow">显示组件,隐藏组件</button>
    <hr>
    <!--v-if是Vue的-->
    <child v-if="show"></child>
    <hr>
</div>
</body>
<script>
    //组件有自己的html,css,js,事件
    //定义一个全局组件
    Vue.component('child', {
        //配置项
        // template:决定了定义的组件的样式
        template: `
          <div>
          <button @click="back">后退</button>
          {{ name }}
          <button @click="forward">前进</button>
          </div>`,
        data() {
            return {
                name: '首页'
            }
        },
        methods: {
            back() {
                alert('后退了')
            },
            forward() {
                alert('前进了')
            },
        },
        // 生命周期钩子1
        beforeCreate() {
            console.log('beforeCreate')
        },
        created() {
            console.log('created')
        },
        beforeMount() {
            console.log('beforeMount')
        },
        mounted() {
            console.log('mounted')
        },
        beforeUpdate() {
            console.log('beforeUpdate')
        },
        updated() {
            console.log('updated')
        },
        beforeDestroy() {
            console.log('beforeDestroy')
        },
        destroyed() {
            console.log('destroyed')
        },
    })
    var vm = new Vue({
        el: '#app',
        data: {
            username: '',
            show: false,
        },
        methods: {
            handleShow() {
                this.show = !this.show
            }
        },
        // Vue的生命周期钩子
        // beforeCreate() {
        //     console.log('beforeCreate')
        // },
        // created() {
        //     console.log('created')
        // },
        // beforeMount() {
        //     console.log('beforeMount')
        // },
        // mounted() {
        //     console.log('mounted')
        // },
        // beforeUpdate() {
        //     console.log('beforeUpdate')
        // },
        // updated() {
        //     console.log('updated')
        // },
        // beforeDestroy() {
        //     console.log('beforeDestroy')
        // },
        // destroyed() {
        //     console.log('destroyed')
        // },

    })
</script>
</html>

 

结果:

Vue的生命周期钩子:

 当开始输入时:

 组件的生命周期钩子:

点击按钮:显示组件

点击按钮:隐藏组件

 

8个生命周期钩子,什么情况会用到?

  - created:用的比较多,变量初始化完成了(data中的数据),在这里,我们发送ajax请求

  - beforeDestroy:组价销毁之前会执行

    - 组件创建,就执行一个定时任务(每隔1秒,打印一个helloworld)

    - 组件销毁,定时任务要销毁,如果定时任务不销毁,会一直执行

 小案例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/vue.js"></script>
</head>
<body>
<div id="app">
    <h5>生命周期钩子</h5>
    <input type="text" v-model="username">---->{{username}}
    <h5>使用组件</h5>
    <button @click="handleShow">显示组件,隐藏组件</button>
    <hr>
    <!--v-if是Vue的-->
    <child v-if="show"></child>
    <hr>
</div>
</body>
<script>
    //组件有自己的html,css,js,事件
    //定义一个全局组件
    Vue.component('child', {
        //配置项
        // template:决定了定义的组件的样式
        template: `
          <div>
          <button @click="back">后退</button>
          {{ name }}
          <button @click="forward">前进</button>
          </div>`,
        data() {
            return {
                name: '首页',
                t:null
            }
        },
        methods: {
            back() {
                alert('后退了')
            },
            forward() {
                alert('前进了')
            },
        },
        // 生命周期钩子1
        beforeCreate() {
            console.log('beforeCreate')
            console.log('当前el状态:', this.$el)
            console.log('当前data状态:', this.$data)
            console.log('当前name状态:', this.name)
        },
        created() {
            console.log('created')
            console.log('当前el状态:', this.$el)
            console.log('当前data状态:', this.$data)
            console.log('当前name状态:', this.name)
            //启动一个定时器:1秒打印一个helloworld
            this.t=setInterval(() =>{
                console.log('helloworld')
            },1000)
        },
        beforeMount() {
            console.log('beforeMount')
            console.log('当前el状态:', this.$el)
            console.log('当前data状态:', this.$data)
            console.log('当前name状态:', this.name)
        },
        mounted() {
            console.log('mounted')
            console.log('当前el状态:', this.$el)
            console.log('当前data状态:', this.$data)
            console.log('当前name状态:', this.name)
        },
        beforeUpdate() {
            console.log('beforeUpdate')
            // el:template(模板),data:数据,name:data中的变量
            console.log('当前el状态:', this.$el)
            console.log('当前data状态:', this.$data)
            console.log('当前name状态:', this.name)
        },
        updated() {
            console.log('updated')
            console.log('当前el状态:', this.$el)
            console.log('当前data状态:', this.$data)
            console.log('当前name状态:', this.name)
        },
        beforeDestroy() {
            console.log('beforeDestroy')
            console.log('当前el状态:', this.$el)
            console.log('当前data状态:', this.$data)
            console.log('当前name状态:', this.name)
            //销毁一个定时器:
            clearInterval(this.t)
            this.t = null
        },
        destroyed() {
            console.log('destroyed')
            console.log('当前el状态:', this.$el)
            console.log('当前data状态:', this.$data)
            console.log('当前name状态:', this.name)
        },
    })
    var vm = new Vue({
        el: '#app',
        data: {
            username: '',
            show: false,
        },
        methods: {
            handleShow() {
                this.show = !this.show
            }
        },
    })
</script>
</html>

 

结果:

点击显示组件:

变量初始化完成了(data中的数据)

点击隐藏组件:

 打印helloworld: 

组件创建,就执行一个定时任务(每隔1秒,打印一个helloworld)

结果:

组件销毁,定时任务要销毁,如果定时任务不销毁,会一直执行:

 结果: