上效果
修改值需要带上解构之前的对象名obj,
changeName:()=>{
// toRefs 解决后变量修改值方法: 解构前变量.字段=新值
obj.name = 'FEIFEI';
}
}
案例源码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>reactive响应式</title>
<script src="js/vue3.3.8/vue.global.js"></script>
<link rel="stylesheet" href="js/elementPlus/index.css">
<script src="js/elementPlus/index.full.js"></script>
</head>
<body>
<div id="app">
{{ id }}
<br/>
{{ name }}
<el-button @click="changeName">修改名称(toRefs之后)</el-button>
</div>
</body>
<script>
const {createApp, ref, toRefs} = Vue
const app = Vue.createApp({
setup(prop, context) {
const {toRefs, reactive} = Vue;
//reactive与toRefs配合使用
let obj = reactive({id: 1, name: 'ls'});
//将变量通过toRefs解析之后,修改变量的值
setTimeout(() => {
obj.id = 111;
}, 2000);
const {id, name} = toRefs(obj);
return {
id,
name,
changeName:()=>{
// toRefs 解决后变量修改值方法: 解构前变量.字段=新值
obj.name = 'FEIFEI妃';
}
}
}
});
app.use(ElementPlus)
app.mount("#app")
</script>
</html>