VUE3(十四)使用计算属性computed和监听属性watch

2021-04-01  本文已影响0人  camellias__

首先,尝试一下计算属性computed

第一种写法

1.png
<template>
  <div>
    <p><input type="text" v-model="age"></p>
    <p><input type="text" v-model="nextAge"></p>
  </div>
</template>
 
<script>
import { computed, ref } from 'vue'
export default {
  setup() {
    const age = ref(18)
    const nextAge = computed(() => {
      return +age.value + 1
    })
    return {
      age,
      nextAge
    }
  }
}

修改age,nextAge会跟着自动+1


2.png

但如果修改nextAge,会有警告:计算属性不能修改


3.png

第二种写法

<template>
  <div>
    <p><input type="text" v-model="age"></p>
    <p><input type="text" v-model="nextAge"></p>
  </div>
</template>
 
<script>
import { computed, ref } from 'vue'
export default {
  setup() {
    const age = ref(18)
    const nextAge = computed({
      get() {
        return +age.value+1
      },
      set(value) {
        console.log(value)  //  输出新修改的值
        return age.value = value - 1
      }
    })
    return { 
      age,
      nextAge
    }
  }
}
 

另一种写法:

使用computed和watch, 一定记得先引入

import { reactive , computed,toRefs,watch} from "vue";

computed属性

使用 getter 函数,并为从 getter 返回的值返回一个不变的响应式 ref 对象。

如图所示,案例:

4.png
<p>原来值:{{ count }}</p>
<p>计算属性更改的值:{{ twoNumber }}</p>
//引用ref函数 可以实时更新数据
import { defineComponent, reactive , computed,toRefs,watch} from "vue";
export default defineComponent({
  name: "HelloWorld",
  setup() {
    const state: any = reactive({
      count: 1,
      twoNumber: computed(() => state.count*2)
    });
  
  
    //暴露出去给外界使用
    //使用toRefs解构响应式对象数据,实现实时更新
    return {
      ...toRefs(state),
    };
  },

watch属性 与 vue2中的 this.$watch (以及相应的 watch 选项) 完全等效。

5.png
 watch(()=>state.count,(newValue, oldValue) => {
     console.log('改变了');
     console.log('我是新的值',newValue);
     console.log('我是旧的值',oldValue);
    })

以上大概就是VUE3中watch与computed的大概用法。

有好的建议,请在下方输入你的评论。

欢迎访问个人博客
https://guanchao.site

上一篇 下一篇

猜你喜欢

热点阅读