【vue】4.0 计算属性和mixins

作者: bobokaka | 来源:发表于2021-05-29 00:21 被阅读0次

实际的html的代码能够简单显示,复杂的计算和运算归类到“计算属性”中。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Examples</title>
<meta name="description" content="">
<meta name="keywords" content="">
<link href="" rel="stylesheet">
<script src="lib/vue.js"></script>
</head>
<body>
    <div id="box">

        {{ myname.substring(0,1).toUpperCase()+ myname.substring(1) }}
        <br/>
        计算属性11111:{{ mycomputedname }}
        <br/>
        方法111111: {{ mycomputedmethod() }}



        <br/>
        计算属性2222:{{ mycomputedname }}
        <br/>
        方法222222: {{ mycomputedmethod() }}
    </div>  

    <script type="text/javascript">
        
      var vm = new Vue({
        el:"#box",
        data:{
          myname:"kerwin"
        },
        methods:{
          mycomputedmethod(){
            console.log("方法mycomputedmethod")
            return this.myname.substring(0,1).toUpperCase()+ this.myname.substring(1)
          }
        },
        computed:{
          //定义一个计算属性
          mycomputedname(){
            //1.必须有返回值
            //2. 每次依赖改变 ,计算属性会重新计算一下
            //3. 缓存(内存)
            console.log("计算属性mycomputedname")
            return this.myname.substring(0,1).toUpperCase()+ this.myname.substring(1)
          }
        }
      })
    </script>
</body>
</html>

计算属性会有缓存,更有效率。但方法每次都会去运算一次。

watch

watch和computed很像。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Examples</title>
<meta name="description" content="">
<meta name="keywords" content="">
<link href="" rel="stylesheet">
<script src="lib/vue.js"></script>
</head>
<body>
    <div id="box">
       
      
        <!-- <button @click="handleClick()">登录</button> -->
        单价<input type="text" v-model="myprice"  />       
        数量<input type="text" v-model="mynumber" /> 
        
        <p>{{sum}}</p>

    </div>  

    <script type="text/javascript">
        
       
        
        var vm = new Vue({
            el:"#box",
            data:{
                myprice:100,
                mynumber:1,
                sum:0
            },
            watch:{
                myprice(){
                    console.log("price改变",this.myprice)

                    if(this.mynumber*this.myprice>1000){
                        this.sum = this.mynumber*this.myprice;
                    }else{
                        this.sum = this.mynumber*this.myprice+100;
                    }
                },
                mynumber(){
                    console.log("number改变",this.mynumber)

                    if(this.mynumber*this.myprice>1000){
                        this.sum = this.mynumber*this.myprice;
                    }else{
                        this.sum = this.mynumber*this.myprice+100;
                    }
                }
            }
        })

        /*
                
            1. @input = "handleInput" 默认传事件对象
            2. @input = "handleInput($event)" 传事件对象

            3. v-model 双向数据绑定指令 -> mvvm (双向数据绑定) ,作用于 表单元素

                    双向绑定是 value(checked) <-----> 状态
         
            4. data 中定义 key值 叫 状态。
         */
    </script>
</body>
</html>

以上代码逻辑也可以通过computed实现

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Examples</title>
<meta name="description" content="">
<meta name="keywords" content="">
<link href="" rel="stylesheet">
<script src="lib/vue.js"></script>
</head>
<body>
    <div id="box">
       
      
        <!-- <button @click="handleClick()">登录</button> -->
        单价<input type="text" v-model="myprice"  />       
        数量<input type="text" v-model="mynumber" /> 
       
        <p>{{computedsum}}</p>

    </div>  

    <script type="text/javascript">
        
       
        
        var vm = new Vue({
            el:"#box",
            data:{
                myprice:100,
                mynumber:1,

            },
            computed:{
                computedsum(){
                    var sum = this.myprice*this.mynumber;

                    if(sum>1000){
                        return sum;
                    }
                    return sum+100;
                }
            }
        })

        /*
                
            1. @input = "handleInput" 默认传事件对象
            2. @input = "handleInput($event)" 传事件对象

            3. v-model 双向数据绑定指令 -> mvvm (双向数据绑定) ,作用于 表单元素

                    双向绑定是 value(checked) <-----> 状态
         
            4. data 中定义 key值 叫 状态。
         */
    </script>
</body>
</html>

computed 和 method 都能实现的一个功能,建议使用 computed,因为有缓存

computed 和 watcher 都能实现的功能,建议使用 computed 因为更加简洁

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>lesson 8</title>
  <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
  <div id="root"></div>
</body>
<script>
  // data & methods & computed & watcher
  // computed 和 method 都能实现的一个功能,建议使用 computed,因为有缓存
  // computed 和 watcher 都能实现的功能,建议使用 computed 因为更加简洁
  const app = Vue.createApp({
    data() {
      return {
        message: "hello world",
        count: 2,
        price: 5,
        newTotal: 10,
      }
    },
    watch: {
      // price 发生变化时,函数会执行
      price(current, prev) {
        this.newTotal = current * this.count;
      }
    },
    computed: {
      // 当计算属性依赖的内容发生变更时,才会重新执行计算
      total() {
        return Date.now() + this.count;
        // return this.count * this.price
      }
    },
    methods: {
      formatString(string) {
        return string.toUpperCase();
      },
      // 只要页面重新渲染,才会重新计算
      getTotal() {
        return Date.now();
        // return this.count * this.price;
      },
    },
    template: `
     <div> {{message}} {{newTotal}} </div>
    `
  });
  const vm = app.mount('#root');
</script>
</html>
Mixins 混入
image.png

目的是提高代码的可复用性。

// 定义一个混入对象
var myMixin = {
  created: function () {
    this.hello()
  },
  methods: {
    hello: function () {
      console.log('hello from mixin!')
    }
  }
}

// 定义一个使用混入对象的组件
var Component = Vue.extend({
  mixins: [myMixin]
})

var component = new Component() // => "hello from mixin!"

比如,数据对象在内部会进行递归合并,并在发生冲突时以组件数据优先。

var mixin = {
  data: function () {
    return {
      message: 'hello',
      foo: 'abc'
    }
  }
}

new Vue({
  mixins: [mixin],
  data: function () {
    return {
      message: 'goodbye',
      bar: 'def'
    }
  },
  created: function () {
    console.log(this.$data)
    // => { message: "goodbye", foo: "abc", bar: "def" }
  }
})

相关文章

网友评论

    本文标题:【vue】4.0 计算属性和mixins

    本文链接:https://www.haomeiwen.com/subject/jsrdsltx.html