vue3定义变量

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>
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值