.orange { color: rgba(255, 165, 0, 1) }

Vue3.0 props

1.你是否遇到了,引用props資料報錯的問題?

在Vue3.0中,採用了proxy,讓很多資料不能直接引用,多的不說直接上解決方法

  1. 首先引入toRefs import { toRefs } from "vue";
  2. props:{
  3. str:String,
  4. obj:Object,
  5. num:Number
  6. }
  7. setup(props){
  8. //讓後在setup中將用toRefs把props轉化成被ref包裹的資料
  9. const { str, obj} = toRefs(props);
  10.  
  11. //這樣你就可以在setup中使用str 和 obj兩個值了
  12. let mystr = str.value;
  13. let myobj = obj.value;
  14. //記住使用時要用 .value ;
  15.  
  16. return {
  17. props
  18. }
  19. }

2.實現父子元件資料雙向繫結,可以雙向修改

在父元件中

//template部分

  1. <template>
  2. <sin-table @handleGetData = "getData" :fatherData="fatherData" />
  3. //通過vue資料傳遞原理把fatherData傳給子元件
  4. </template>

//script部分

  1. import {ref} from "vue"
  2. setup(){
  3. let fatherData = ref('');
  4. const getData = (data) => {
  5. fatherData.value = data; //這裡是通過子元件傳過來的資料修改fatherData;
  6. }
  7. }

在子元件中

//script部分

  1. props:{ fatherData:String }
  2. setup(props,ct) {
  3.  
  4. const changeChildData = (childData) = {
  5.  
  6. //通過emit把childData傳給父元件
  7. ct.emit("handleGetData",childData);
  8. //這樣就實現了,父子元件的雙向資料繫結
  9.  
  10. }
  11.  
  12. return { props }
  13. }

如果fatherData為Object資料,內部子集內容可以直接在子元件中修改,或通過v-model修改

  1. 例如:
  2. import {toRefs} from "vue";
  3. props:{ fatherData:Object };
  4. setup(){
  5. const {fatherData} = toRefs(props);
  6. fatherData.value[0].name = '新狗';
  7. return {
  8. props
  9. }
  10. }