今天在项目中使用reactive过程中出现变量无法更新视图,reactive通常用于对象
<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}}
})
注意ref声明的变量必须用.value赋值实现响应式。
如果是reactive声明的话,需要用forEach去逐个处理,直接复制并不能响应式处理
const cities: string[] = reactive(['北京', '上海','广州','深圳']);const checkedCities:string[]=reactive([]) const handleCheckAllChange=(val:boolean)=>{if(val){cities.forEach(item=>{checkedCities.push(item)})}else{checkedCities.splice(0)}}