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>

posted @ 2021-09-27 17:03  Edith6  阅读(1050)  评论(0编辑  收藏  举报