項(xiàng)目中VUE3常規(guī)用法

關(guān)于setup基礎(chǔ)用法可看vue3基礎(chǔ)

一、通過ref獲取元素實(shí)例

  • 父組件
<template>
   <ref-test ref="testRef" />
</template>
<script>
import { ref, watch, computed, nextTick } from 'vue'
setup() {
  const testRef = ref(null)
  testRef.value.handle()
  return { testRef}
}
</script>
 
  • 子組件
    常規(guī)用法
<script>
export default {
  setup() {
    const handle = () => {
      console.log(11)
    }
    return { handle}
  }
}
</script>

setup語法糖用法

<script setup lang="ts">
import { defineExpose } from 'vue'
const handle = () => {
  console.log(11)
}
// 將方法或數(shù)據(jù)暴露出去
defineExpose({ handle })
</script> 

二、$nextTick使用

在vue中直接引入使用

import { ref, watch, computed, nextTick } from 'vue'
nextTick(() => {})

三、props傳值

  • 父組件
<ref-test :propsTest="1234" />
  • 子組件
    常規(guī)用法
<script>
export default {
  props: { propsTest: Number },
  setup(props) {
  //父組件傳過來的值
    console.log(props.propsTest)  }
}
</script>

setup語法糖用法

<script setup>
// defineProps 不需要引入,它們將自動地在 <script setup> 中可用
 const props = defineProps({
   propsTest: Number
 })
 console.log(props.propsTest)
</script>

四、emit向上傳遞

  • 父組件
<ref-test  @updateEmit="updateEmit($event)" />
<script>
setup() {
const updateEmit = (value) => {
 console.log( value )
}
 return { updateEmit }
}
</script>
  • 子組件
    常規(guī)用法
<div @click="testEmit()">點(diǎn)我</div>

<script>
export default {
  setup(props, { emit }) {
    //   emit向上傳遞
    const testEmit = () => {
      emit('updateEmit', 2112)
    }
    return { testEmit }
  }
}

setup語法糖用法

<div @click="testEmit()">點(diǎn)我</div>

<script setup lang="ts">
// defineEmits 不需要引入,它們將自動地在 <script setup> 中可用
// emit向上傳遞
const emit = defineEmits(['updateEmit'])
const testEmit = () => {
  emit('updateEmit', 2112)
}
</script>

五、獲取router

<script lang="ts">
import { useRouter } from 'vue-router'
setup() {
   const $router = useRouter()
   console.log($router.currentRoute)
</script>
}

六、計(jì)算屬性

用法比較常規(guī)

import {  watch, computed} from 'vue'
setup() {
   const comp = ref(0)
   const count = ref(1)
    // 計(jì)算屬性
    const plusOne = computed(() => count.value + 1)
    console.log(plusOne.value, 90)
    // 監(jiān)聽
    watch(comp, (newV, oldV) => {
      console.log(newV, oldV, 88)
    })
}

七、數(shù)據(jù)監(jiān)聽

1、監(jiān)聽ref的值

const num= ref("")
watch(num, (newV, oldV) => {
    console.log(newV, oldV, 88);
});

2、監(jiān)聽reactive的值

const obj= reactive({
 str: "",
})
watch(() => obj.str, (newV, oldV) => {});

原因:vue無法監(jiān)聽對象內(nèi)部的值,需要將值return出去監(jiān)聽
3、監(jiān)聽多個值

// 監(jiān)聽num,和str的值
watch([num,() => obj.str], (newV, oldV) => {
  console.log(newV[0],newV[1])
  console.log(oldV[0],oldV[1])
});
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容