vue3 组件生命周期,watch和computed

背景:

Uncaught (in promise) ReferenceError: Cannot access 'state' before initialization

翻译成中文:

Uncathed(in promise)引用错误:初始化前无法访问"state"

错误原因:

在watch里面想要修改组件生命周期中创建的reactive({})创建的动态数据

错误代码如下:

<script setup>

import { reactive, ref, watch } from "vue";

import { useRoute, useRouter } from "vue-router";

const ruleForm = ref();

const router = useRouter();

const props = defineProps({

isAdd: {

type: String,

default: "add",

},

});

const emits = defineEmits("clickBack");

const getBack = () => {

emits("clickBack", "add");

};

//生命周期的触发时机。watch在onMounted之前

watch(

() => props.isAdd,

(newValue, oldValue) => {

console.log('ajiang>>>', newValue);

if (newValue === "edit") {

state.homeType = "edit";

} else {

state.homeType = "add";

}

},

{

immediate: true,

deep: true

}

);

const state = reactive({

loading: false,

homeTitle: "航次测算",

homeBack: "返回上级",

homeType: "add", //edit

});

</script>

修改思路:

修改代码如下:

javascript 复制代码
const props = defineProps({
    isAdd: {
        type: String,
        default: "add",
    },
});
const isAdd = computed(() => {
    return props.isAdd
})
watch(
    () => isAdd,
    (newValue, oldValue) => {
        console.log('ajiang>>>', newValue);
        if (newValue === "edit") {
            state.homeType = "edit";
        } else {
            state.homeType = "add";
        }
    },
    {
        immediate: true,
        deep: true
    }
);
相关推荐
Penge6667 小时前
《Go 后端开发者学 TypeScript:数组和元组》
javascript
Penge6668 小时前
《Go 后端开发者学 TypeScript:export关键字大全》
javascript
Penge6668 小时前
《Go 后端开发者学 TypeScript:从零理解 async、await 与 Promise》
javascript
Penge6668 小时前
typescript 中const用法
javascript
Csvn9 小时前
Monorepo
前端
Csvn9 小时前
流水线
前端
Csvn9 小时前
微前端架构
前端
Linux-lucky10 小时前
45-Linux学习之旅之防火墙与WEB加固
linux·前端·网络·学习·ubuntu
风骏时光牛马13 小时前
生成一个移动端标题,只需要一个标题,不需要其他的任何文本。
前端
IT_陈寒13 小时前
Redis雪崩把我坑惨了,这是5年经验的教训
前端·人工智能·后端