Vue3中ref和reactive的使用

今天在项目中使用reactive过程中出现变量无法更新视图,reactive通常用于对象

javascript 复制代码
<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>
javascript 复制代码
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
        }
    }
})

注意ref声明的变量必须用.value赋值实现响应式。

如果是reactive声明的话,需要用forEach去逐个处理,直接复制并不能响应式处理

javascript 复制代码
 const cities: string[] = reactive(['北京', '上海','广州','深圳']);
 const checkedCities:string[]=reactive([])    
 const handleCheckAllChange=(val:boolean)=>{
    if(val){
        cities.forEach(item=>{
           checkedCities.push(item)
       })
    }else{
        checkedCities.splice(0)
    }
    
 }
相关推荐
li35743 小时前
将已有 Vue 项目通过 Electron 打包为桌面客户端的完整步骤
前端·vue.js·electron
Icoolkj4 小时前
VuePress 与 VitePress 深度对比:特性、差异与选型指南
前端·javascript·vue.js
excel4 小时前
CNN 分层详解:卷积、池化到全连接的作用与原理
前端
excel4 小时前
CNN 多层设计详解:从边缘到高级特征的逐层学习
前端
^Rocky5 小时前
JavaScript性能优化实战
开发语言·javascript·性能优化
西陵5 小时前
Nx带来极致的前端开发体验——任务编排
前端·javascript·架构
大前端helloworld6 小时前
从初中级如何迈入中高级-其实技术只是“入门卷”
前端·面试
笑鸿的学习笔记6 小时前
JavaScript笔记之JS 和 HTML5 的关系
javascript·笔记·html5
东风西巷7 小时前
Balabolka:免费高效的文字转语音软件
前端·人工智能·学习·语音识别·软件需求