• Vue computed计算和watch监听


    目录

    computed计算,从现有数据计算出新的数据

    案例:水果名称过滤

    computed计算总价

    监听

    案例 计算

    案例

    案例-watch监听todolist本地存储

    localStorage的使用

    在A页面中先存储: 

    在B页面中使用:

     类的绑定

    class样式悬停 :class=“{‘active‘:循环项==index}“ ,切换

    data

    methods  

    数组语法

    样式绑定

    Style内联样式 

    回顾js数组 方法



    watch,computed和methods 的关系

    1. watch和computed都是以Vue的依赖追踪机制为基础 的,它们都试图处理这样一件事情:当某一个数据(称它为依赖数据)发生变化的时候,所有依赖这个数据的“相关”数据“自动”发生变化,也就是自动调用相关的函数去实现数据的变动。

    2.对methods:methods里面是用来定义函数的,很显然,它需要手动调用才能执行。而不像watch和computed那样,“自动执行”预先定义的函数

    watch和computed各自处理的数据关系场景不同

    1. watch 擅长处理的场景: 一个数据影响多个数据

    2. computed擅 长处理的场景: 一个数据受多个数据影响

    watch和computed的区别

    1、功能上:computed是计算属性,watch是监听一个值的变化,然后执行对应的回调。
    2、是否调用缓存:computed中的函数所依赖的属性没有发生变化,那么调用当前的函数的时候会从缓存中读取,而watch在每次监听的值发生变化的时候都会执行回调。
    3、是否调用return:computed中的函数必须要用return返回,watch中的函数不是必须要用return。
    4、computed默认第一次加载的时候就开始监听;watch默认第一次加载不做监听,如果需要第一次加载做监听,添加immediate属性,设置为true(immediate:true)
    5、使用场景:computed----当一个属性受多个属性影响的时候,使用computed-----购物车商品结算。watch–当一条数据影响多条数据的时候,使用watch-----搜索框.

    computed计算,从现有数据计算出新的数据

    computed是计算属性,主要作用是把数据存储到内存中,减少不必要的请求,还可以利用computed给子组件的data赋值。

    computed用来监控自己定义的变量,该变量不在data里面声明,直接在computed里面定义,然后就可以在页面上进行双向数据绑定展示出结果或者用作其他处理。

    1. <body>
    2. <div id="app">
    3. <input type="text" v-model.number="n1">
    4. <input type="text" v-model.number="n2">
    5. <p>{{n3}}p>
    6. <p>{{rstr}}p>
    7. div>
    8. body>
    9. <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js">script>
    10. <script>
    11. new Vue({
    12. el: "#app",
    13. computed: {
    14. //从现有的n1与n2计算出n3
    15. "n3": function () {
    16. return this.n1 + this.n2;
    17. },
    18. //rstr是从现有的str算出
    19. rstr() {
    20. return this.str.split('').reverse().join("");
    21. }
    22. },
    23. data() {
    24. return {
    25. n1: 1,
    26. n2: 2,
    27. str: "明天放假15天"
    28. }
    29. }
    30. })
    31. script>

    案例:水果名称过滤

    1. 搜索水果

    2. {{item}}
  • computed计算总价

    1. <body>
    2. <div id="app">
    3. <table border="1">
    4. <tr>
    5. <th>选择th>
    6. <th>商品名称th>
    7. <th>价格th>
    8. <th>数量th>
    9. tr>
    10. <tr v-for="item in goods" :key="item.name">
    11. <td><input type="checkbox" v-model="item.sel">td>
    12. <td>{{item.name}}td>
    13. <td>{{item.price}}td>
    14. <td><button @click="item.num++">{{item.num}}button>td>
    15. tr>
    16. table>
    17. <p>总价:{{total}},共{{count}}件p>
    18. div>
    19. body>
    20. <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js">script>
    21. <script>
    22. new Vue({
    23. el: "#app",
    24. data() {
    25. return {
    26. goods: [{
    27. name: "javacript入门",
    28. price: 20,
    29. num: 2,
    30. sel: true,
    31. }, {
    32. name: "vue实战",
    33. price: 80,
    34. num: 5,
    35. sel: false,
    36. }]
    37. }
    38. },
    39. computed: {
    40. total() {
    41. //返回的默认总价
    42. var n = 0;
    43. this.goods.forEach(item => {
    44. //累加数量 * 加载
    45. if (item.sel)
    46. n += item.price * item.num;
    47. })
    48. //返回
    49. return n;
    50. },
    51. count() {
    52. //返回默认件数
    53. var n = 0;
    54. this.goods.forEach(item => {
    55. //累加数量
    56. if (item.sel)
    57. n += item.num;
    58. })
    59. //返回
    60. return n;
    61. }
    62. }
    63. });
    64. script>

    监听

    定义:监听数据的变化,执行回调函数

    值类型监听

    1. watch:{
    2. "num":function(){
    3. ......
    4. }
    5. }

    案例 计算

    1. <body>
    2. <div id="app">
    3. <h1>watch监听-计算h1>
    4. <input type="text" v-model.number="obj.pre">
    5. <select name="" id="" v-model="obj.type">
    6. <option value="+">+option>
    7. <option value="-">-option>
    8. <option value="*">*option>
    9. <option value="/">/option>
    10. select>
    11. <input type="text" v-model.number="obj.next">
    12. ={{obj.result}}
    13. div>
    14. body>
    15. <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js">script>
    16. <script>
    17. new Vue({
    18. el: "#app",
    19. data() {
    20. return {
    21. obj: {
    22. pre: 1,
    23. type: "+",
    24. next: 1,
    25. result: 2,
    26. }
    27. }
    28. },
    29. watch: {
    30. //引用类型数据监听需要添加deep选项
    31. //oval和nval都是最新的值
    32. "obj": {
    33. handler(nval, oval) {
    34. // 只要obj发生变化重新计算result的值
    35. this.obj.result = eval(`${this.obj.pre}${this.obj.type}${this.obj.next}`)
    36. },
    37. deep: true,
    38. }
    39. }
    40. });
    41. script>

    引用类型监听
            nval 数据最新的值
            oval 数据之前的值

    1. watch:{
    2. obj:{
    3. handler(nval){...},
    4. deep:true
    5. }
    6. }

    案例

    1. <body>
    2. <div id="app">
    3. <h1>watch监听h1>
    4. <button @click="obj.pre++">{{obj.pre}}button>
    5. div>
    6. body>
    7. <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js">script>
    8. <script>
    9. new Vue({
    10. el: "#app",
    11. data() {
    12. return {
    13. obj: {
    14. pre: 5,
    15. }
    16. }
    17. },
    18. watch: {
    19. //引用类型数据监听需要添加deep选项
    20. //oval和nval都是最新的值
    21. "obj": {
    22. handler(nval, oval) {
    23. console.log("数据发生变化", oval, nval);
    24. },
    25. deep: true,
    26. }
    27. }
    28. });
    29. script>

    案例-watch监听todolist本地存储

    1. <body>
    2. <div id="app">
    3. <input type="text" @keyup.enter="addItem">
    4. <h3>未完成{{undolist.length}}h3>
    5. <div v-for="item in undolist" :key="item.title">
    6. <input type="checkbox" v-model="item.done">
    7. <span>{{item.title}}span>
    8. <button @click="delItem(item)">xbutton>
    9. div>
    10. <h3>已经完成{{donelist.length}}h3>
    11. <div v-for="item in donelist" :key="item.title">
    12. <input type="checkbox" v-model="item.done">
    13. <span>{{item.title}}span>
    14. <button @click="delItem(item)">xbutton>
    15. div>
    16. div>
    17. <script>
    18. new Vue({
    19. el: "#app",
    20. computed: {
    21. // 通过计算list算出undolist没有完成的列表
    22. undolist() {
    23. // 通过list过滤 返回item.done值为false的所有元素
    24. return this.list.filter(item => !item.done);
    25. },
    26. donelist() {
    27. // 返回保留item.done值为true的元素
    28. return this.list.filter(item => item.done);
    29. }
    30. },
    31. methods: {
    32. // 删除元素
    33. delItem(item) {
    34. // 查找item在list的下标
    35. var ind = this.list.indexOf(item);
    36. // 进行删除
    37. this.list.splice(ind, 1);
    38. },
    39. // 添加元素
    40. addItem(e) {
    41. // e.target输入的文本框
    42. // e.target.value 文本框的值
    43. this.list.unshift({ done: false, title: e.target.value })
    44. // 清空文本框的内容
    45. e.target.value = "";
    46. }
    47. },
    48. data() {
    49. return {
    50. //从本地localStorage获取数据,获取不到就用默认
    51. list: JSON.parse(localStorage.getItem("done") || '[{ "done": true, "title":"学习html" }]')
    52. }
    53. },
    54. watch: {
    55. "list": {
    56. handler() {
    57. //监听list的变化,存储todo数据
    58. localStorage.setItem("done", JSON.stringify(this.list))
    59. },
    60. deep: true,
    61. }
    62. },
    63. })
    64. // 目标:1 在文本框输入文字,按回车,文字添加到list里面
    65. // 目标:2 单击x 删除当前行
    66. // unshift在数组的前面添加一个元素
    67. // splice(n,m,j) 从第n个删除m个,添加j
    68. // indexOf(item) 查找item在列表的下标
    69. script>

    localStorage的使用

    localStorage.getItem(key):获取指定key本地存储的值
    localStorage.setItem(key,value):将value存储到key字段

    在A页面中先存储: 

    1. var imgs = obj_mainform.archivesId //声明个变量存储下数据
    2. localStorage.setItem('key',imgs); //将变量imgs存储到name字段

    在B页面中使用:

    var naid = localStorage.getItem("key"); //获取指定key本地存储的值

     类的绑定

    1.给v-bind:class 设置一个对象,可以动态地切换class,例如:

  • 最终渲染结果:


    2、对象中也可存在多个属性,动态切换class,:class 可以合class共存

  •  最终渲染结果:

    class样式悬停 :class=“{‘active‘:循环项==index}“ ,切换

    1. <div class="picBtn">
    2. <span v-for="(item, index) in listBtn" :key="index"
    3. :class="{ active: btnActive === index }" @click="choosePic(index)">
    4. {{ item }}
    5. span>
    6. div>

    data

    1. listBtn:['图一','图二'],
    2. btnActive:0,//默认选中图一

    methods  

    1. choosePic(index){
    2. this.btnActive = index;//获得点击元素的index
    3. },

    数组语法

    我们可以把一个数组传给 :class,以应用一个 class 列表:

    1. <style>
    2. .active {
    3. color: aqua;
    4. background-color: blanchedalmond;
    5. }
    6. .big {
    7. font-size: large;
    8. }
    9. .bold {
    10. color: red;
    11. }
    12. style>
    13. <body>
    14. <div id="app">
    15. <button @click="flag=!flag" v-bind:class="flag?active:''">开关button>
    16. <button @click="flag=!flag" :class="{'active':flag,'big':isbig}">开关button>
    17. <p :class="classlist" 这是行测试文本>p>
    18. div>
    19. <script>
    20. new Vue({
    21. el: "#app",
    22. data() {
    23. return {
    24. flag: true,
    25. isbig: true,
    26. classlist: ['bold', 'big', 'active']
    27. }
    28. }
    29. })
    30. script>

    样式绑定

    1. <body>
    2. <div id="app">
    3. <input type="color" v-model="color">
    4. <input type="range" min="1" max="200" v-model="height">
    5. <p :style="{'fontSize':'48px','backgroundColor':color,'lineHeight':height+'px'}">样式的绑定p>
    6. div>
    7. <script>
    8. new Vue({
    9. el: "#app",
    10. data() {
    11. return {
    12. color: "#f00",
    13. height: 80
    14. }
    15. }
    16. })
    17. script>

    Style内联样式 

    对象语法:
    CSS 属性名可以用驼峰式 (camelCase) 或短横线分隔 (kebab-case,记得用引号括起来) 来命名


    数组语法

    回顾js数组 方法

    http://t.csdn.cn/5ku8Thttp://t.csdn.cn/5ku8T

  • 相关阅读:
    【小程序-开篇】国内IT技术圈的技能树貌似点歪了?
    常见弱口令汇编
    Java毕业设计-网上宠物店系统
    windows环境下Git安装与远程仓库SSH Keys配置
    python最优化算法实战---线性规划之内点法
    Raven2靶机渗透
    华为手机日历的功能大全,赶快来试试
    南京邮电大学电工电子(数电)实验报告——二进制全加器 & 数据选择器 & 集成触发器
    rust - 一个日志缓存记录的通用实现
    数字集成电路设计(三、Verilog HDL程序设计语句和描述方式)(一)
  • 原文地址:https://blog.csdn.net/m0_59642141/article/details/126977581