【一】setup函数
- 如果使用配置项API---》写起来跟vue2一样
- 如果写组合式API---》所有代码都要写在setup函数中
<template>
<div class="home">
<h2>姓名:{{ name }}</h2>
<h2>年龄:{{ age }}</h2>
<button @click="handleAdd">点击加年龄</button>
<button @click="changeName">点击变名字</button>
</div>
</template>
<script>
import {ref} from 'vue'
export default {
name: 'HomeView',
setup() {
let name = ref('hope')
let age = ref(25)
// function handleAdd(){
// age.value+=1
// }
const handleAdd = () => {
age.value += 1
}
const changeName =() => {
name.value='Tom'
}
return {
name,
age,
handleAdd,
changeName,
}
}
}
</script>
【二】ref和reactive
- ref 包裹值类型[数字,字符串,布尔],做成响应式
- reactive包裹引用类型[对象,数组],做成响应式
- 使用reactive包裹的对象,直接通过 . [] 取值赋值就是响应式的
- ref包裹的对象,需要使用 对象.value 修改值
- 使用ref包裹的,在template中,使用 变量.value
<template>
<div class="home">
<h1>ref响应式</h1>
<h2>姓名:{{ name }}</h2>
<h2>年龄:{{ age }}</h2>
<button @click="handleAdd">点击加年龄</button>
<button @click="changeName">点击变名字</button>
<hr>
<h1>reactive响应式</h1>
<h2>爱好:{{ hobby }}</h2>
<h2>{{person.name}}--{{person.age}}--{{person.height}}</h2>
<button @click="changeHeight">点击变身高</button>
</div>
</template>
<script>
import {reactive, ref} from 'vue'
export default {
name: 'HomeView',
setup() {
let name = ref('hope')
let age = ref(25)
const handleAdd = () => {
age.value += 1
}
const changeName =() => {
name.value='Tom'
}
const hobby = ref('篮球')
const person = reactive({
name:'hope',
age:25,
height:175
})
const changeHeight=()=>{
person.height+=1
}
return {
name,
age,
handleAdd,
changeName,
hobby,
person,
changeHeight
}
}
}
</script>
【三】计算属性
<style>
</style>
<template>
<div class="about">
<h1>计算属性</h1>
<p>姓:<input type="text" v-model="person.firstName"></p>
<p>名:<input type="text" v-model="person.lastName"></p>
<p>全名:{{ person.fullName }}</p>
<p>全名修改:<input type="text" v-model="person.fullName"></p>
</div>
</template>
<script>
import {computed, reactive} from "vue";
export default {
setup() {
const person = reactive({
firstName:'',
lastName:''
})
// 只有 计算属性,不修改值的情况
person.fullName=computed(() => {
return person.firstName+person.lastName
})
// 支持修改
person.fullName=computed({
get(){
return person.firstName+person.lastName
},
set(value){
person.firstName = value.slice(0, 1)
person.lastName = value.slice(1)
}
})
return {
person,
}
},
}
</script>