016:尚硅谷计算属性computed学习示例

This commit is contained in:
heiye111
2025-10-02 11:01:36 +08:00
parent 79e7ed9597
commit ad4201836c

View File

@@ -1,13 +1,10 @@
<template>
<div class="person">
:<input v-model="firstName"></input> <br>
:<input v-model="lastName"></input> <br>
<h2>姓名:{{ fullName }}</h2> <br>
<button @click="computedd">修改姓</button> <br>
<h3>一辆{{brand}}汽车的价格是:{{ jg }}万元!</h3>
<button @click="changePrice">加价10万元</button>
<h3>我的游戏:</h3>
<ul>
<li v-for="game in games" :key="game.id">{{game.name}}</li>
</ul>
<button @click="changeGame">添加新游戏</button>
</div>
@@ -15,34 +12,30 @@
<script setup lang="ts">
import { reactive, ref, toRefs, toRef } from 'vue';
let car = reactive({
brand: '奔驰',
price: 100,
color: '黑色',
})
let { brand, price, color } = toRefs(car);
let jg = toRef(car, 'price');
console.log(brand, price, color);
import { reactive, ref, computed } from 'vue';
let firstName = ref('zahng');
let lastName = ref('san');
let games = ref([
{ name: '游戏1', id: 10 },
{ name: '游戏2', id: 20 },
{ name: '游戏3', id: 30 }
]);
function changePrice() {
price.value += 10;
console.log(price.value);
}
function changeGame() {
games.value = [{ name: '游戏1', id: 10 },
{ name: '游戏2asdasd', id: 20 },
{ name: '游戏3', id: 30 }];
// Object.assign(games, [{ name: '游戏1saddsa222', id: 10 },
// { name: '游戏2asdas', id: 20 },
// { name: '游戏3', id: 30 }]);
}
let fullName = computed({
get(){
return firstName.value.slice(0, 1).toUpperCase() + firstName.value.slice(1) + '-' + lastName.value.slice(0, 1).toUpperCase() + lastName.value.slice(1)
},
set(val){
console.log('set', val);
// 分割字符串
return val.split('-').forEach((item, index) => {
if (index === 0) {
firstName.value = item;
} else {
lastName.value = item;
}
})
}
})
function computedd() {
fullName.value = 'li-si';
}
</script>