First, try to calculate the attribute calculated
The first way of writing
<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
}
}
}
Modify age, nextAge will automatically +1
But if you modify nextAge, there will be a warning: the calculated attribute cannot be modified
The second way of writing
<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
}
}
}
Another way of writing:
Use computed and watch, you must remember to introduce it first
import {
reactive , computed,toRefs,watch} from "vue";
computed attribute
Use the getter function and return an unchanging responsive ref object for the value returned from the getter.
As shown in the figure, the case:
<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),
};
},
The watch attribute is exactly equivalent to this.$watch (and the corresponding watch option) in vue2.
watch(()=>state.count,(newValue, oldValue) => {
console.log('改变了');
console.log('我是新的值',newValue);
console.log('我是旧的值',oldValue);
})
The above is probably the general usage of watch and computed in VUE3.
Have a good suggestion, please enter your comment below.
Welcome to personal blog
https://guanchao.site
Welcome to the Mini Program: