首页 > 其他分享 >vue-计算属性、监听属性、生命周期钩子函数

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

时间:2023-09-19 17:13:46浏览次数:32  
标签:el vue console log 钩子 name 组件 data 属性

计算属性

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)

结果:

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

 结果:

 

标签:el,vue,console,log,钩子,name,组件,data,属性
From: https://www.cnblogs.com/Lucky-Hua/p/17714441.html

相关文章

  • 安装node、npm和vue3
    1.首先安装node和npmnode.js安装地址https://nodejs.org/en/download/2.下载完安装好后,打开终端命令验证是否安装成功node-vnpm-v3.安装vue3npminstall-g@vue/cli4.创建vue3项目npmcreate【your-project-name】这一指令将会安装并执行create-vue,它是......
  • Vue之后端交互、计算、监听、组件间通信
    一、与后端交互三种方式1、2、3、4、小电影案例html:<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>Title</title><scriptsrc="https://cdn.jsdelivr.net/npm/vue/dist/vue.js&q......
  • vue:run时报错:EACCES: permission denied([email protected])
    一,报错信息:[eslint]EACCES:permissiondenied,open'/data/vue/responsive/node_modules/.cache/eslint/43541cdc.json’如图:二,解决切换拒绝访问的文件的ownerliuhongdi@lhdpc:/data/vue/responsive$sudochownliuhongdi.liuhongdi-R/data/vue/responsive/node......
  • vue:安装使用nprogress([email protected])
    一,官方地址:官方站:https://rstacruz.github.io/nprogress/代码站:https://github.com/rstacruz/nprogress二,安装/引入:1,安装root@lhdpc:/data/vue/responsive#npminstallnprogress —save2,main.js中引入:123456789101112131415161718......
  • 【Vue】大悟!MVVM模型
    hello,我是小索奇,精心制作的Vue教程持续更新哈,想要学习&巩固&避坑就一起学习叭~MVVM模型Vue虽然没有完全遵循MVVM模型,但Vue的设计也收到了它的启发在文档中也会使用VM(ViewModel的缩写)这个变量名表示Vue实例(Vue作者参考了MVVM模型,并非其创建的)img模型说明M:模型Model-对应data中的数......
  • Vue-与后端交互的三种方式、箭头函数、显示电影小案例
    与后端交互的三种方式前后端需要打通-----》从前端发送ajax-----》ajax的核心:使用js发送http请求,接收返回-原生js,可以开启ajax,但是原生js开启,比较麻烦,需要做浏览器兼容,有坑(基本不写)-jq,写了个兼容所有浏览器的$.ajax(),不仅仅有ajax,还封装了很多dom操作-如......
  • 12-Vue核心-绑定样式
    class与style绑定1)在应用界面中,某个(些)元素的样式是变化的2)class/style绑定就是专门用来实现动态样式效果的技术class绑定样式写法:v-bind:class ="xxx"或:class="xxx",xxx可以是字符串、对象、数组1)字符串写法适用于:只绑定一个样式,类名不确定,需要动态获取2)数......
  • spring中 beandefinition类中的6大属性
    什么是BeanDefinition?BeanDefinition表示bean的定义,spring根据 beandefinition用来创建bean对象,他有很多属性来描述bean。1.beanClass:表示一个bean的类型,比如UserService.class,在创建bean的过程中会根据此属性来实例化得到的对象。2.scope:表示一个bean的作用域,比如......
  • 谷歌浏览器提示:尝试通过Set-Cookie标头设置Cookie时被阻止,因为它具有“Secure“属性,但
    具体表现是使用谷歌浏览器https访问网址可以正常操作cookie,但是http访问,就会发现cookie不能操作,比如无法进行正常的登录。解决方案:清除谷歌浏览器的缓存数据。 参考链接:https://blog.csdn.net/Mr_yangx/article/details/115674652 ......
  • Vue收集表单数据
    收集表单数据v-model的使用data:{ account:'',//用户输入 password:'', age:'', sex:'',//需要配置 hobby:[], agree:''}若,则v-model收集的是value值,用户输入的就是value值。若,则v-model收集的是value值,需要配置value值。性别:男<inputtype=&qu......