学习目标:
vue3 +ts 实现数据双向绑定
学习内容:
使用ref()函数
在看很多别人的博客文档中说,ref函数传入的为基本数据类型,reactive函数传入的为引用类型,但是在实际运用时,用ref传入一个数组也是可以的,相反我假如直接用reactive传入数组,赋值以后他不会同步更新页面,,,,
<template>
<div class="welcome">
<div>选择一个玩具</div>
<div>
<button v-for="(item,index) in list" :key="index" @click="handle(item)">{
{
index}}:{
{
item}}</button>
</div>
<div>你选择了{
{
checkitem}}玩具</div>
</div>
</template>
<script lang="ts">
import {
defineComponent,ref } from 'vue';
export default defineComponent({
name: 'Welcome',
setup(){
const list=ref([
"坦克",
"手枪",
"奥特曼"
])
const checkitem=ref('')
const handle=(item:string)=>{
checkitem.value=item
}
return{
list,
checkitem,
handle
}
}
});
</script>
<style lang="less" scoped>
</style>
使用reactive()函数
<template>
<div>
<div>选择一个玩具</div>
<div>
<button v-for="(item,index) in data.list" :key="index" @click="data.handle(item)">{
{
item}}</button>
</div>
<div>你选择了{
{
data.checkitem}}玩具</div>
</div>
</template>
<script lang='ts'>
import {
defineComponent, reactive} from 'vue'
interface dataobj{
//定义为接口类型,更加详细的定义对象里的每个属性值类型
list:Array<any>,
checkitem:String,
handle:(item:string)=>void,//定义为函数类型,入参为字符串类型:无返参的普通函数
[propName:string]:any,//该对象还可加入任意属性值类型
};
export default defineComponent({
name:'four',
setup(){
const data=reactive({
list:[ "坦克","手枪","奥特曼"],
checkitem:'',
handle:(item:string)=>{
data.checkitem=item
}
}) as dataobj
return{
data //抛出一个对象,模板中用 对象.属性名 获取想要的属性值
}
}
})
</script>
<style>
</style>
使用toRefs()函数
<template>
<div>
<div>选择一个玩具</div>
<div>
<button v-for="(item,index) in list" :key="index" @click="handle(item)">{
{
item}}</button>
</div>
<div>你选择了{
{
checkitem}}玩具</div>
</div>
</template>
<script lang='ts'>
import {
defineComponent, reactive,toRefs} from 'vue'
interface dataobj{
//定义为接口类型,更加详细的定义对象里的每个属性值类型
list:Array<any>,
checkitem:String,
handle:(item:string)=>void,//定义为函数类型,入参为字符串类型:无返参的普通函数
[propName:string]:any,//该对象还可加入任意属性值类型
};
export default defineComponent({
name:'four',
setup(){
const data=reactive({
list:[ "坦克","手枪","奥特曼"],
checkitem:'',
handle:(item:string)=>{
data.checkitem=item
}
}) as dataobj
return{
...toRefs(data) //抛出一个对象传入toRefs,将toRefs返回出的值将其解构后仍具有响应特性,视图不再用.属性名来获取值
}
}
})
</script>
<style>
</style>