来看下vue2的写法
<template>
<div>
{{ textValue }}
{{ textComputed }}
<button @click="handleBtn">点击改变</button>
</div>
</template>
<script>
export default {
name: 'Test',
data() {
return {
textValue: '111111'
}
},
computed: {
textComputed() {
if (this.textValue.length > 0) {
return '我有值'
} else {
return '我没有值'
}
}
},
methods: {
handleBtn() {
if (!this.textValue) {
this.textValue = '11111'
} else {
this.textValue = ''
}
}
}
}
</script>
vue3写法,因为vue3采用的是API的写法还是有一定的区别
<template>
<div>
{{ textValue }}
{{ textComputed }}
<button @click="handleBtn">点击改变</button>
</div>
</template>
<script setup>
import { computed, ref } from "vue"
const textValue = ref('1111111')
const textComputed = computed(() => {
if (textValue.value.length > 0) {
return '我有值'
}
return '我没有值'
})
const handleBtn = () => {
if (!textValue.value) {
textValue.value = '11111'
} else {
textValue.value = ''
}
}
</script>
<style lang="scss" scoped>
</style>
其实在vue3中还有一种写法,还有一种写法,就是在vue3都出来可以让定义出来的某一个类型是只读的状态,要是强行修改会在控制台收到警告提示,那我们就要采用另外一种写法
<script setup>
import { computed, ref } from "vue"
const firstName = ref('John')
const lastName = ref('Doe')
const fullName = computed({
get() {
return firstName.value + '' + lastName.value
},
set(value) {
[firstName.value, lastName.value] = value.split(' ')
}
})
</script>
总结:其实在在计算属性中改变最大的就是写法上的改变
1,直接是包含computed的对象中
2,vue3直接采用api的方式进来的写法
3,补充一点vue3在初始化模版如果没有默认的div不会报错