|
@@ -1,57 +1,54 @@
|
|
|
<template>
|
|
|
- <h2>toRefs</h2>
|
|
|
- <!-- <h3>name: {{ state2.name }}</h3>
|
|
|
- <h3>age: {{ state2.age }}</h3> -->
|
|
|
-
|
|
|
- <h3>name: {{ name }}</h3>
|
|
|
- <h3>age: {{ age }}</h3>
|
|
|
-
|
|
|
- <h3>name2: {{ name2 }}</h3>
|
|
|
- <h3>age2: {{ age2 }}</h3>
|
|
|
+ <h2> toRaw 与 markRaw</h2>
|
|
|
+ <h3>state: {{ state }}</h3>
|
|
|
+ <hr>
|
|
|
+ <button @click="testToRaw">测试toRaw</button>
|
|
|
+ <button @click="testMarkRow">测试markRaw</button>
|
|
|
</template>
|
|
|
|
|
|
<script lang="ts">
|
|
|
-import { defineComponent, reactive, toRef, toRefs } from "vue";
|
|
|
-function useFeature() {
|
|
|
- const state = reactive({
|
|
|
- name2: "xiaoming",
|
|
|
- age2: 18,
|
|
|
- });
|
|
|
- return {
|
|
|
- ...toRefs(state)
|
|
|
- }
|
|
|
+import { defineComponent, markRaw, reactive, toRaw } from 'vue'
|
|
|
+interface userInfo{
|
|
|
+ name: string,
|
|
|
+ age: number,
|
|
|
+ likes?: string[]
|
|
|
}
|
|
|
export default defineComponent({
|
|
|
- //toRefs 把一个响应式对象转化成普通对象 该普通对象的每个 property都是一个ref
|
|
|
- setup() {
|
|
|
- const state = reactive({
|
|
|
- name: "xiaoming",
|
|
|
- age: 18,
|
|
|
- });
|
|
|
- const state2 = toRefs(state)
|
|
|
- console.log(state)
|
|
|
- console.log(state2)
|
|
|
- const { name, age } = toRefs(state);
|
|
|
- //解决: 利用toRefs可以将一个响应式reactive 对象的所有原始属性转化为ref属性
|
|
|
- //应用: 当从而成函数返回响应式对象时,可以在不丢失响应式的情况下对返回的对象进行分解使用
|
|
|
- const {name2,age2} = useFeature()
|
|
|
- setInterval(() => {
|
|
|
- // state.name += '='
|
|
|
- // state2.name.value += '!'
|
|
|
- name.value += "!!!!";
|
|
|
- name2.value += '!!!!'
|
|
|
- }, 2000);
|
|
|
+ setup () {
|
|
|
+ const state = reactive<userInfo>({
|
|
|
+ name:'zs',
|
|
|
+ age: 18
|
|
|
+ })
|
|
|
+ const testToRaw = ()=>{
|
|
|
+ //把代理对象编程普通对象 数据变化 页面不变化
|
|
|
+ const user = toRaw(state)
|
|
|
+ user.name += '=='
|
|
|
+ console.log(111)
|
|
|
+ }
|
|
|
+ const testMarkRow = ()=>{
|
|
|
+ // state.likes = ['吃','喝']
|
|
|
+ // state.likes[0] += '='
|
|
|
+ // console.log(state)
|
|
|
+ const likes = ['吃','喝']
|
|
|
+ state.likes = markRaw(likes)
|
|
|
+ //markRaw标记独享的数据,从此以后都不能成为代理对象了
|
|
|
+ setInterval(()=>{
|
|
|
+ if(state.likes){
|
|
|
+ state.likes[0] += '='
|
|
|
+ console.log('定时器启动')
|
|
|
+ }
|
|
|
+ },1000)
|
|
|
+ }
|
|
|
+
|
|
|
return {
|
|
|
- // ...state,
|
|
|
- // state2
|
|
|
- name,
|
|
|
- age,
|
|
|
- name2,
|
|
|
- age2
|
|
|
- };
|
|
|
- },
|
|
|
-});
|
|
|
+ state,
|
|
|
+ testToRaw,
|
|
|
+ testMarkRow
|
|
|
+ }
|
|
|
+ }
|
|
|
+})
|
|
|
</script>
|
|
|
|
|
|
<style scoped>
|
|
|
+
|
|
|
</style>
|