vue3 script setup小記


官網地址:https://v3.cn.vuejs.org/api/sfc-script-setup.html

  <template>
      <Map ref="ref_map"/>
  </template>
<script setup>
  import {
    computed,
    reactive,
    ref,
    watchEffect,
    watch,
    nextTick,
    toRefs,
    onMounted,
    defineProps,
    defineEmits,
    useSlots, 
    useAttrs
  } from "vue";

  import { useRouter, useRoute } from 'vue-router'

  import Map from "./components/map.vue"  //組件直接引入即可使用,不需注冊

  const slots = useSlots()
  const attrs = useAttrs()

  //setup標簽 中的變量和函數 不需要return
  const state = reactive({
    color:"red",
    previewData:{}
  })
  const num = ref("")
  //賦值時 ref類型需要用value  reactive則不需要
  num.value = "ref"
  // ts語法中以下沒有在原對象中聲明的會報紅線  加上// @ts-ignore即可
  // @ts-ignore
  state.previewData.url = "reactive"



  const router = useRouter()        //路由跳轉等信息 相當於 $router

  const route = useRoute()          // $route

  const props = defineProps({       //使用 props 接收傳值
    foo: String,
  })

  //使用 $emit-------start-----
    const emit = defineEmits(['clickHandler'])   

    function clickHandler (e) {
      emit("clickHandler", e)
    }
  //使用 $emit-------end-------


  //訪問子組件變量、函數等---start------
    //父組件
    const ref_map = ref({})       
    ref_map.value.fontSizeAdap(5)  //注意:所有變量函數,均在value中

    // 子組件
    defineExpose({      // 暴露需要訪問的變量、函數 供父組件使用
      state,
      fontSizeAdap
    })
  //訪問子組件變量、函數等---end---------


  // <script setup> 中可以使用頂層 await。結果代碼會被編譯成 async setup()
  const post = await axios(`/api/post/1`).then(r => r.json())

  // 監聽屬性
  //原watch
  watch(state.color, (newval, oldValue) => {})
  // watchEffect: 監視所有回調中使用的數據,默認立即執行,自動的收集依賴
  watchEffect(()=>{
      console.log(state.color,"state.color")
  })

  //計算屬性
  const count = computed(() => num + 1)


</script>
  <style>
  /* 狀態驅動的動態 CSS */
  /* script setup中語法,且支持JS表達式 ,(需要用引號包裹起來)*/
  h1{
    color: v-bind('state.color');
  }
  /* script 中語法 */
  h1{
    color: v-bind(color);
  }
</style>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



猜您在找 Vue3 script setup 語法糖詳解 vue3 setup方法 Vue3 setup詳解 vue3