菜鸟的博客

纵有疾风起,人生不言弃。

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

冲刺记录13-vue的响应式数据1

ref

基本类型的响应式数据

  • 首先需要 import {ref} from 'vue'
  • 哪个需要响应式,哪一个加ref('name')
  • 在函数中调用响应式数据的时候,需要name.value
<template>
    <div class="person">
        <h2>姓名:{{name}}</h2>
        <h2>年龄:{{age}}</h2>
        <button @click="changeName">修改名字</button>
        <button @click="changeAge">修改年龄</button>
        <button @click="showTel">查看联系方式</button>
    </div>
</template>

<script lang="ts" name="Person" setup>
        import {ref} from 'vue'
        //数据部分
        let name = ref('张三')
        let age = ref(18)
        let tel = '13383619197'
        //函数部分
        function changeName(){
            name.value = 'zhang-san'
        }
        function changeAge(){
            age.value += 1
        }
        function showTel(){
            alert(tel)
        }
</script>

<style scoped>
.person{
    background-color: skyblue;
    box-shadow: 0 0 10px;
    border-radius: 10px;
    padding:20px;
}
button{
    margin: 0 5px;
}
</style>

对象类型的响应式数据

  • 把reactive换为ref即可,但是在函数中调用的时候要.value,具体示例代码如下:
<template>
    <div class="person">
     <h2>游戏列表:</h2>
     <ul>
        <li v-for="g in games" :key="g.id">{{g.name}}</li>
     </ul>
     <button @click="changeName">修改第一个游戏的名字</button>
    </div>
</template>

<script lang="ts" name="Person" setup>
import {ref} from 'vue'

let games = ref([
    {id:'123',name:'王者荣耀'},
    {id:'456',name:'火影忍者'},
    {id:'789',name:'原神'}
])

function changeName(){
    games.value[0].name = '英雄联盟'//注意这里的数组怎么.value
}
</script>

<style scoped>
.person{
    background-color: skyblue;
    box-shadow: 0 0 10px;
    border-radius: 10px;
    padding:20px;
}
button{
    margin: 0 5px;
}
li{
    font-size: 20px;
}
</style>

posted on   hhmzd233  阅读(8)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示