vue3如何定义变量

 更新时间:2026年05月16日 14:13:27   作者:冰凉小脚  
文章主要讲述了Vue中ref和reactive两种定义变量的方法,ref适用于简单类型数据,需在setup中定义并return,通过.value获取和操作;reactive适用于复杂数据,注意在使用时正确调用变量

1、定义变量

1.1、ref

一般用来处理简单类型的数据

注意点:

  • 定义变量在setup函数中用vue的ref方法
  • 定义的变量以及方法需要setup函数进行return出来,才可以在html代码中使用
  • 方法中调用变量需要打点到变量的value进行获取和操作
<template>
    <div>
        <div class="count">
            count: {{ count }}
        </div>
        <button @click="countaddFn">count++</button>
    </div>
</template>

<script>
import { ref } from 'vue';

export default {
    setup () {
        let count=ref(0)
        let countaddFn=()=>{
            
            count.value++
        }
        return {
            count,countaddFn
        }
    }
}
</script>

1.2、reactive

一般用于定义复杂数据

<template>
    <div>
        <table border="1">
            <tr>
                <th>id</th>
                <th>姓名</th>
                <th>年龄</th>
                <th>性别</th>
            </tr>
            <tr v-for="item in user" :key="item.id">
                <td>{{ item.id }}</td>
                <td>{{ item.name }}</td>
                <td>{{ item.age }}</td>
                <td>{{ item.gender }}</td>
            </tr>
        </table>
        <button @click="modifyTheFn">修改数据</button>
    </div>
</template>

<script>
import { reactive } from 'vue';

export default {
    setup () {
        // 复杂类型数据定义
        let user=reactive([
            {id:1,name:'张三',age:20,gender:'男'},
            {id:2,name:'李四',age:30,gender:'中性'},
            {id:3,name:'王五',age:40,gender:'女'},
            {id:4,name:'老六',age:50,gender:'未知'},
        ])
        function modifyTheFn(){
            user[1].name='老七'
        }
        return {
            user,modifyTheFn
        }
    }
}
</script>

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

最新评论