初次使用vue3 通过reactive 做响应式处理时,发现更新了数据,试图不更新问题。代码是这样写的
<template>
<div>
<div>
数据:{{ dataList.name }}
</div>
<el-button type="primary" @click="btnFn()">修改数据</el-button>
</div>
</template>
<script lang="ts" setup>
import {
reactive,
} from 'vue'
let dataList = reactive({
name:'张三',
});
const btnFn = async () => {
dataList = {
name:'李四',
};
console.log(dataList)
}
</script>
查阅资料说是需要内部再加个对象
改为:
<template>
<div>
<div>
数据:{{ dataList.data.name }}
</div>
<el-button type="primary" @click="btnFn()">修改数据</el-button>
</div>
</template>
<script lang="ts" setup>
import {
reactive,
} from 'vue'
const dataList = reactive({
data: {
name: '张三',
}
});
const btnFn = async () => {
dataList.data = {
name: '李四',
};
console.log(dataList)
}
</script>
通过这种方式确实会更新视图。具体内部方法实现我暂未去看源码内部实现,待后续再看
网友评论