计算属性普通函数写法 和 set get 写法

特点:

  1. 定义的时候,要被定义为“方法”
  2. 在使用计算属性的时候,当普通的属性使用即可
  3. 计算属性会缓存计算的结果,只有计算属性依赖的数据变化时,才会重新进行运算

好处:

  1. 实现了代码的复用
  2. 只要计算属性中依赖的数据源变化了,则计算属性会自动重新求值!
    普通写法
<template>
  <div>
    <p>和为: {{ num }}p>
    <p>{{ reverseMessage }}p>
  div>
template>

<script>
export default {
  data() {
    return {
      a: 10,
      b: 20,
      message: "我是个字符串",
    };
  },
  computed: {
    num() {
      return this.a + this.b;
    },
    reverseMessage() {
      return this.message.split("").reverse().join("");
    },
  },
};
script>

复杂写法

<template>
    <div>
        
        <div>性别是:{{getsex}}</div>
        <button @click="addarr">添加</button>
        <div>改变name的值 {{getname}}</div>
    </div>
</template>
 
<script>
    export default {
        name: "newsdetail",
        data(){
            return{
               sex:['男','女'],
                first: 'wang',
                two: 'kun'
            }
        },
        computed: {
            // 每个计算属性都包括一个getter(get)和一个setter(set)
            //在计算属性内填写的函数相当于简写的get
            getsex:function (){
                //计算属性函数中的return不能少
                return this.sex[0]
            },
            getname:{
                get: function () {
                    console.log('调用了fullName的get方法');
                    return this.first + ' ' + this.two;
                },
                //只有当getname中的值改变的时候才能触发set,传值的value是getname改变的值
                set: function (value) {
                    console.log('调用了fullName的set方法',value);
                    const names = value.split(' ');
                    this.first = names[0];
                    this.two= names[1];
                }
 
            }
        },
        methods:{
            addarr:function (){
                this.getname='jiang ke'
            }
        }
    }
</script>
 
<style scoped>
 
</style>

你可能感兴趣的:(vue,vue.js,前端,javascript)