import { ref } from 'vue'
const count = ref(0)
<div>{{count}}</div>
console.log(count) console.log(count.value)
<template> <div> <div>{{ num }}</div> <div>{{ age }}</div> <button @click="inc">inc</button> </div> </template> <script setup> import { ref } from 'vue' let num = 1 const age = ref(12) const inc = () => { num++ age.value++ } </script>
import { reactive } from 'vue'
const obj = reactive({ id: 10, name: 'gz' })
<div>{{obj.id}} - {{obj.name}}</div>
const done = () => { obj.id = 20 } console.log(obj)
const age = ref(12) const state = reactive({ id: 1, name: 'xh' }) const obj = ref({ id: 1, name: 'xh' }) console.log(age, state, obj);
const count = reactive(10)
let obj = reactive({ id: 10, name: 'gz' }) const done = () => { obj = { id: 20, name: 'gl' } }
const { id, name } = obj
. 创建简单的响应式变量时,当然只能 ref()
. 如果需要简单的对象,ref()、reactive() 都可以
. 层级比较深的对象,请使用 reactive()
<span @click="changeTheme" :class="['iconfont', darkMode ? 'icon-Sun' : 'icon-Moon-Star']"> </span>
import { ref } from 'vue' const darkMode = ref(false) const changeTheme = () => { darkMode.value = !darkMode.value }
[] 优化
使用内联事件完成 - 省略事件处理函数 changeTheme 的定义
使用三元表达式 - 更直观
<span @click="darkMode = !darkMode" class="iconfont" :class="darkMode ? 'icon-Sun' : 'icon-Moon-Star'"> </span>
import { ref } from 'vue' const darkMode = ref(false)