VUE中的CompositionAPI绑定
1.一个文件
<template>
<div>
姓名:<input v-model="userName" /> {{ userName }} <br />
薪水:<input type="number" v-model="salary" /> <br />
<button v-on:click="submit">提交</button>
<hr />
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
const userName = ref('小白123')
const salary = ref(100)
function submit() {
salary.value += 1000
}
</script>
<style scoped>
.iterInfo {
background-color: aquamarine;
widows: 80%;
}
.iterInfo span {
background-color: chocolate;
margin-left: 10px;
border: 1px;
border-radius: 5px;
}
</style>
2.新增文件
import { ref } from 'vue'
export default function () {
const userName = ref('小白123')
const salary = ref(100)
function submit() {
salary.value += 1000
}
return {
userName,
salary,
submit,
}
}
引用
<script setup lang="ts">
import mySalary from './components/mySalary'
const { userName, salary, submit } = mySalary()
</script>
3.也可以使用ref来定义变量,然后在script标签中使用
<script setup lang="ts">
// import mySalary from './components/mySalary'
// const { userName, salary, submit } = mySalary()
// 也可以使用ref来定义变量,然后在script标签中使用
// 注意:使用ref定义的变量,需要使用.value来获取值
import { ref } from 'vue'
const userName = ref('小白')
const salary = ref(100)
function submit() {
salary.value += 100
}
</script>
4.也可以使用reactive来定义对象变量,然后在script标签中使用需要转toRef
<script setup lang="ts">
// import mySalary from './components/mySalary'
// const { userName, salary, submit } = mySalary()
// 也可以使用ref来定义变量,然后在script标签中使用
// 注意:使用ref定义的变量,需要使用.value来获取值
import { reactive, ref, toRef, toRefs } from 'vue'
// const userName = ref('小白')
// const salary = ref(100)
// function submit() {
// salary.value += 100
// }
// 也可以使用reactive来定义变量,然后在script标签中使用需要转toRef
// 注意:使用reactive定义的变量,不需要使用.value来获取值
const salaryInfo = reactive({
userName: '小白',
salary: 100,
})
// 方式一 逐个属性转换
// const userName = toRef(salaryInfo, 'userName')
// const salary = toRef(salaryInfo, 'salary')
// 方式二 整个对象转换
const { userName, salary } = toRefs(salaryInfo)
function submit() {
salary.value += 100
}
</script>