VUE3.0 學習筆記-創建數據,props傳參、watch監聽、計算屬性computed


  • 創建vue實例
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
  •  vue3 新建元素 (ref、reactive、toRefs
//ref 創建 字符串形式數據 ((vue2 是寫在data中)) const sendVal = ref("");
const name = ref("年糕");
const age = ref(20);

// reactive 創建對象數據
const msg = reactive({
      name: "張三",
      age: 18,
      dbZhang: computed(() => {
        return `雙倍年紀${msg.age * 2}`;
      }),
 });

// 函數創建(vue2 是寫在methods中)

function add() {
      console.log(age);
      age.value += 1;
}

//最重要的,需要將這些新創建的 return 出來 

setup() {  //在setup 中創建數據與函數 (將上面都寫在setup中)
  ....  
  ....
  ....
  return { name, age, dbAge, add, ...toRefs(msg), add02, sendMsg, sendVal };
}
  • vue3 props 傳參
// 父組件

 <HelloWorld child="我是傳的參數" @accept="sendMsg"></HelloWorld>

//父組件接收子組件的傳參
function sendMsg(params) {
      sendVal.value = params; // senVal 為上面創建的空字符串數據,賦值時為 sendVal.value 
      msg.name = params;
 }

也需要將sendMsg 在setup 函數中 return 出去

  

//子組件 props: { child: String, }, 
setup(props, context) {
const childs = ref(props.child);
function send() {
context.emit("accept", "子組件傳參"); //因為沒有this 所以需要 context }
return { childs, send }; },
  • watch 進行數據監聽
watch在監聽 ref 類型時和監聽reactive類型時watch函數的寫發有所不一樣。 
watch(
    //watch 監聽 reactive 類型 () => msg.age, (newVal, oldVal, clean) => { console.log(msg.name + newVal, oldVal); clean(() => { console.log("clean"); }); }, name, //watch在監聽 ref 類型時: (newVal, oldVal) => { console.log(newVal, oldVal); }, );

  watchEffect 它與 watch 的區別主要有以下幾點:

  1. 不需要手動傳入依賴
  2. 每次初始化時會執行一次回調函數來自動獲取依賴
  3. 無法獲取到原值,只能得到變化后的值
watchEffect(() => {
          console.log(state.count)
          console.log(state.name)
          /*  初始化時打印:
                  0
                  zs

            1秒后打印:
                  1
                  ls
          */
          })

  watch和watchEffect監聽器在同一個頁面中都可以使用多次,對於分別監聽多個變量的時候

  •  vue3 計算屬性 computed
const dbAge = computed(() => {
      return `我的年紀${age.value * 2}`;
   }); //直接寫在變量聲明中

const msg = reactive({
      name: "張三",
      age: 18,
      dbZhang: computed(() => {
        return `雙倍年紀${msg.age * 2}`;
      }),
    });

  

  


免責聲明!

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



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM