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
    }
);
相关推荐
暖木生晖2 小时前
Javascript函数之匿名函数以及立即执行函数的使用方法?
开发语言·javascript·ecmascript
一 乐2 小时前
医疗管理|医院医疗管理系统|基于springboot+vue医疗管理系统设计与实现(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·医疗管理系统
光影少年2 小时前
React Native第六章
javascript·react native·react.js
晓得迷路了2 小时前
栗子前端技术周刊第 105 期 - npm 安全性加强、Storybook 10、htmx 4.0 Alpha 1...
前端·javascript·npm
七号练习生.c3 小时前
CSS入门
前端·css·tensorflow
程序员爱钓鱼3 小时前
Python编程实战——Python实用工具与库:Matplotlib数据可视化
前端·后端·python
程序员爱钓鱼3 小时前
Python编程实战 - Python实用工具与库 - requests 与 BeautifulSoup
前端·后端·python
wyzqhhhh3 小时前
前端跨页面通信
前端
G018_star sky♬3 小时前
原生JavaScript实现输入验证的界面
javascript·css·css3
火龙谷3 小时前
DrissionPage遇到iframe
开发语言·前端·javascript