The use of ref and reactive in Vue3

Today, variables cannot update the view in the process of using reactive in the project. Reactive is usually used for objects

<template>
    <div class="wrapper">
        <el-checkbox :indeterminate="isInderterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
        <el-checkbox-group v-model="checkedCities">
            <el-checkbox v-for="(city,index) in cities" :key="index" :label="city" @click="">{
   
   {city}}</el-checkbox>
        </el-checkbox-group>
    </div>
</template>
<script lang="ts" src="./insight-4d-test.ts"></script>
<style lang="scss" scoped src="./insight-4d-test.scss"></style>
import { defineComponent, onMounted, ref, reactive,getCurrentInstance } from "@vue/composition-api"
export default defineComponent({
    setup(props, { root }) {
        const instance: any = getCurrentInstance();
        const checkAll:boolean=ref(false);
        // var checkedCities:string[] = reactive([]);
        var checkedCities = ref<string[]>([]);
        const cities: string[] = reactive(['北京', '上海','广州','深圳']);
        
        const handleCheckAllChange=(val:boolean)=>{
            checkedCities.value=val?cities:[]
        }
        return{
            checkAll,
            checkedCities,
            cities,
            handleCheckAllChange
        }
    }
})

Note that the variables declared by ref must use .value assignment to implement responsiveness.

If it is a reactive statement, you need to use forEach to process it one by one, and direct copying cannot be processed in a responsive manner

 const cities: string[] = reactive(['北京', '上海','广州','深圳']);
 const checkedCities:string[]=reactive([])    
 const handleCheckAllChange=(val:boolean)=>{
    if(val){
        cities.forEach(item=>{
           checkedCities.push(item)
       })
    }else{
        checkedCities.splice(0)
    }
    
 }

Guess you like

Origin blog.csdn.net/qq_30596783/article/details/132365209