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>

猜你喜欢

转载自blog.csdn.net/Binglianxiaojiao/article/details/128983584