Vue3.0+Vite(2)

98 阅读1分钟

Ref

被ref包装之后需要.value 来进行赋值

<script setup>
import { ref } from 'vue'
const msg = ref('hello world')

const handleMsgChange = ()=>{
  msg.value = 'hello everyone'
}
</script>

<template>
  <h1>{{ msg }}</h1>
  <button type="button" @click="handleMsgChange">点击修改文字</button>
  
</template>

Reactive

<script setup>
import { ref , reactive} from 'vue'
const msg = ref('hello world')
let person = reactive({
   name:'ms',
})
const handleMsgChange = ()=>{
  msg.value = 'hello everyone';
  person.name = 'masai'
}
</script>

<template>
  <h1>{{ msg }}</h1>
  <h1>{{person.name}}</h1>
  <button type="button" @click="handleMsgChange">点击修改文字</button>
  
</template>

toRefs

<script setup>
import {reactive, toRefs } from 'vue'
const obj = reactive({
   foo: 1,
   bar: 1
})
let { foo, bar } = toRefs(obj)
// bar 转化为响应式对象
const change = () => {
   foo.value++
   bar.value++
}
</script>

<template>
  <h1>{{ foo }}</h1>
  <h1>{{ bar }}</h1>
  <button type="button" @click="change">点击改变</button>

</template>

computed

<script setup>
import {ref, computed } from 'vue'
const price = ref('123')

const priceMsg = computed(()=>{
    return '$'+price.value
})

</script>

<template>
  <div>
    {{priceMsg}}
  </div>
</template>
<script setup>
import {ref, computed } from 'vue'
const price = ref('123')

const priceMsg = computed({
      get: () => price.value,
      set(val) {
        price.value = '¥' + val
      }
})

</script>

<template>
  <div>
    {{priceMsg}}
  </div>
  <button @click="priceMsg = 666">click</button>
</template>

watch

<script setup>
import { watch, ref, reactive } from 'vue'
const name = ref('ms')
  const otherName = reactive({
    firstName: '马',
    lastName: '赛'
  })
  watch(name, (newValue, oldValue) => {
    // 输出 马赛 ms
    console.log(newValue, oldValue)
  })
  // watch 可以监听一个函数的返回值
  watch(
    () => {
      return otherName.firstName + otherName.lastName
    },
    value => {
      // 当otherName中的 firstName或者lastName发生变化时,都会进入这个函数
      console.log(`我叫${value}`)
    }
  )

  setTimeout(() => {
    name.value = '马赛'
    otherName.firstName = '王'
  }, 3000)
</script>

<template>
  <div>
    {{name}}
  </div>
</template>

watchEffect

<script setup>
import { watchEffect, ref } from 'vue'
const id = ref('0')
watchEffect(() => {
  // 先输出 0 然后两秒后输出 1 id value的变化产生变化。
  console.log(id.value)
})

setTimeout(() => {
  id.value = '1'
}, 2000)
</script>

<template>
  <div>
    {{id}}
  </div>
</template>