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
    }
);
相关推荐
万少1 天前
HarmonyOS 开发必会 5 种 Builder 详解
前端·harmonyos
橙序员小站1 天前
Agent Skill 是什么?一文讲透 Agent Skill 的设计与实现
前端·后端
炫饭第一名1 天前
速通Canvas指北🦮——基础入门篇
前端·javascript·程序员
王晓枫1 天前
flutter接入三方库运行报错:Error running pod install
前端·flutter
符方昊1 天前
React 19 对比 React 16 新特性解析
前端·react.js
ssshooter1 天前
又被 Safari 差异坑了:textContent 拿到的值居然没换行?
前端
曲折1 天前
Cesium-气象要素PNG色斑图叠加
前端·cesium
Forever7_1 天前
Electron 淘汰!新的桌面端框架 更强大、更轻量化
前端·vue.js
不会敲代码11 天前
前端组件化样式隔离实战:React CSS Modules、styled-components 与 Vue scoped 对比
css·vue.js·react.js
Angelial1 天前
Vue3 嵌套路由 KeepAlive:动态缓存与反向配置方案
前端·vue.js