Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2 - ref 全家桶 #2732

Open
MioFeatherDust opened this issue May 25, 2024 · 0 comments
Open

2 - ref 全家桶 #2732

MioFeatherDust opened this issue May 25, 2024 · 0 comments

Comments

@MioFeatherDust
Copy link

MioFeatherDust commented May 25, 2024

<script setup lang="ts">
import { ref, Ref, reactive ,computed} from "vue"

const initial = ref(10)
const count = ref(0)

// Challenge 1: Update ref
function update(value:number) {
  // 直接赋值
  count.value = value
}

/**
 * Challenge 2: Check if the `count` is a ref object.
 * Make the output be 1
*/
// 判断类型与对象中是否有value值
function isRef<T>(value: unknown): value is Ref<T> {  
  return value && typeof value === 'object' && 'value' in value;  
}  
  
console.log(  
  isRef(count) ? 1 : 0  
);  

/**
 * Challenge 3: Unwrap ref
 * Make the output be true
*/
function initialCount(value: number | Ref<number>) {
  // Make the output be true
  if(isRef(value)){
    value = value.value
  }
  console.log(value === 10)
}

initialCount(initial)

/**
 * Challenge 4:
 * create a ref for a property on a source reactive object.
 * The created ref is synced with its source property:
 * mutating the source property will update the ref, and vice-versa.
 * Make the output be true
*/
const state = reactive({
  foo: 1,
  bar: 2,
})
//计算属性双向绑定
const fooRef = computed({  
  get: () => state.foo,  
  set: (newValue) => (state.foo = newValue),  
});  
// mutating the ref updates the original
fooRef.value++
console.log(state.foo === 2)

// mutating the original also updates the ref
state.foo++
console.log(fooRef.value === 3)

</script>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant