首页 > 其他分享 >vue的响应式数据1

vue的响应式数据1

时间:2024-05-16 23:54:14浏览次数:9  
标签:vue name ref value 响应 10px 数据

 

所花时间(包括上课):  1  h左右
代码量(行):  200     左右
搏客量(篇): 1
了解到的知识点:  用ref定义响应式数据
备注(其他):  

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>

标签:vue,name,ref,value,响应,10px,数据
From: https://www.cnblogs.com/muzhaodi/p/18197005

相关文章