首先在vue3中实现变量动态话是靠组合式api中的ref或者reactive
一.reactive有局限性:
1.仅对对象、数组类型有效,对string、unmber、boolean无效
<template> <div @click="changReactive">{{ numberRective }}{{ stringRective }}{{ booleanRective }}</div> </template> <script setup> import {reactive} from 'vue' const numberRective = reactive(9) const stringRective = reactive('字符串') const booleanRective = reactive(true) console.log(numberRective,stringRective,booleanRective,'可以打印') //动态修改就会出现报错 // function changReactive(){ // numberRective = 10 // stringRective = '被改变的字符串' // booleanRective = false // console.log(numberRective,stringRective,booleanRective,'但是不能动态化无效') // } </script>
2.使用reactive声明string unmber boolean 并动态修改会出现一下报错:
二.ref的包裹性:
1.ref返回的都是一个ref对象,对应的值要 .value 才能拿到
<template> <div>{{ firstRef }}</div> </template> <script setup> import {ref} from 'vue' const firstRef = ref(9) console.log(firstRef,'打印的是一个ref对象') console.log(firstRef.value,'打印9') </script>
2.在模板中用{{ }}这个语法可以自动解包,不需要 .value
<template> <div>{{ firstRef }}</div> </template> <script setup> import {ref} from 'vue' const firstRef = ref(9) </script>
个人总结:感觉那个顺眼就用哪个,干脆用ref算了