<template>
<div>
<h2>{{nameAll}}</h2>
<h2>{{method}}</h2>
<h2>{{tt()}}</h2>
<h2>{{firstName}}</h2>
<h2>更新后赋值数据:{{lastName}}</h2>
<h2>赋值数据:{{writeValue}}</h2>
<button @click="tt">vue2数据更新</button>
</div>
</template>
<script lang ='ts' name='VueTwo'>
export default{
data(){
return {
firstName:"wu",
lastName:"liuqi"
}
},
computed:{
nameAll:function(){
return this.firstName + this.lastName
},
method(){
return 111
},
writeValue:{
get:function(){//也可以写为get(){} 页面显示数据会调用这个方法
return this.firstName + this.lastName
},
set:function(value){//也可以写为set(value){} 赋值数据会调用这个方法
this.lastName = value
return value
}
}
},
methods:{
tt(){
this.writeValue = "alilailail"
}
}
}
</script>
<style>
</style>
页面效果:
下面是vue3 computed函数的代码示例:
<template>
<div class="ttt">
<button @click="updateReactive2">更新数据</button>
<h2>{{fullName}}</h2>
<h2>{{name3}}</h2>
</div>
</template>
<script setup lang="ts" name="testName">
import {ref} from 'vue'
import {reactive} from 'vue'
import {toRefs} from 'vue'
import {toRef} from 'vue'
import {computed} from 'vue'
function updateReactive2(){
fullName.value = "啦啦啦啦啦"
}
let name3 = ref('李莉莉')
let fullName = computed({
get(){
return name3
},
set(value){
console.log("赋值方法")
name3.value = value
}
})
</script>
<style>
.ttt{
color:red
}
</style>
页面效果: