vue3.0 基礎用法 {ref,watch,computed,reactive, toRefs,onMounted}

<template>
  <div class="about">
    <h1>{{msg}}</h1>
    <button @click="changeFn">改變</button>
    <div class="block">
      <div @click="changeShow">{{isShow? '隱藏' : '顯示' }}</div>
      <div v-if="isShow"> dsfsdfads</div>
    </div>    
    <div class="block">
      {{double}}/{{count}}
      <button @click="changecount">增加</button>
      <ul><li v-for="item in options" :key="item.name">{{item.name}}</li></ul>
    </div>
  </div>
</template>
<script>
let api = () =>{ // 模仿axios api
  return new Promise((resolve,reject)=>{
    setTimeout(()=>{
      let res = {
        status:0,
        data:[{name:'測試'}]
      }
      resolve(res)
    },1000)
  })
}
import {ref,watch,computed,reactive, toRefs,onMounted} from 'vue'
export default {
  setup() {
    onMounted(() => {
      console.log('掛在了')
      data.count++;
      getList()
    })
    const data = reactive({ // reactive定義變量
      count: 1,
      options:[],
      double: computed(() => { // 計算屬性
        return data.count * 2
      }),
      changecount: () => {
        data.count++
      },
    })

    let msg = ref('我是中國人'); // ref定義變量
    let isShow = ref(false);
    const changeFn=()=>{
      msg.value = msg.value == '你是小日本' ? "我是中國人" : '你是小日本';
    }
    const changeShow=()=>{
      isShow.value = !isShow.value
    }

    watch(msg,(newVal, oldVal)=>{ // 單個監聽 
        console.log(newVal, oldVal)
    })
    watch(()=>data.double,(newVal, oldVal)=>{ // 單個監聽 
        console.log(newVal, oldVal,"===data.double")
    },// { deep: true } // 深度監聽
    )
    // watch([msg, ()=>data.double],(newVal, oldVal)=>{ // 多個監聽: ["我是中國人", 2],["你是小日本", 1]
    //     console.log(newVal, oldVal)
    // })

    const getList = async ()=>{ // 請求示例
      let res =  await api();
      data.options = res.data || []
      console.log(data.options)
    }

    return {
      msg,isShow,changeFn,changeShow,
      ...toRefs(data) // 平鋪reactive定義
    }
  },
}
</script>
<style lang='less' scoped>
.block{
  border:1px solid #ccc;
  padding: 20px;margin: 20px;;
}
</style>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章