.orange { color: rgba(255, 165, 0, 1) }
Vue3.0 props
1.你是否遇到了,引用props資料報錯的問題?
在Vue3.0中,採用了proxy,讓很多資料不能直接引用,多的不說直接上解決方法
- 首先引入toRefs import { toRefs } from "vue";
- props:{
- str:String,
- obj:Object,
- num:Number
- }
- setup(props){
- //讓後在setup中將用toRefs把props轉化成被ref包裹的資料
- const { str, obj} = toRefs(props);
- //這樣你就可以在setup中使用str 和 obj兩個值了
- let mystr = str.value;
- let myobj = obj.value;
- //記住使用時要用 .value ;
- return {
- props
- }
- }
2.實現父子元件資料雙向繫結,可以雙向修改
在父元件中
//template部分
- <template>
- <sin-table @handleGetData = "getData" :fatherData="fatherData" />
- //通過vue資料傳遞原理把fatherData傳給子元件
- </template>
//script部分
- import {ref} from "vue"
- setup(){
- let fatherData = ref('');
- const getData = (data) => {
- fatherData.value = data; //這裡是通過子元件傳過來的資料修改fatherData;
- }
- }
在子元件中
//script部分
- props:{ fatherData:String }
- setup(props,ct) {
- const changeChildData = (childData) = {
- //通過emit把childData傳給父元件
- ct.emit("handleGetData",childData);
- //這樣就實現了,父子元件的雙向資料繫結
- }
- return { props }
- }
如果fatherData為Object資料,內部子集內容可以直接在子元件中修改,或通過v-model修改
- 例如:
- import {toRefs} from "vue";
- props:{ fatherData:Object };
- setup(){
- const {fatherData} = toRefs(props);
- fatherData.value[0].name = '新狗';
- return {
- props
- }
- }