Vue3 uses script setup to cause this.$route to not take effect

Vue3 uses script setup to cause this.$route to not take effect

describe

<script setup>
import { reactive } from "vue";
const data = reactive({
    form: {
        id:this.$route.params.id
    }
})

</script>

I originally wanted to this.$routeget the id passed in, but the result was an error:

TypeError: Cannot read properties of undefined (reading '$route')

After some tossing, it was found that it was the reason of this pointer. Since setup is called before other component options are resolved, this will not be a reference to the active instance.

In order to avoid our wrong use, Vue changed this to undefined

solution

Use the useRoute() method to get the route

<script setup>
import { reactive } from "vue";
import { useRoute } from "vue-router";

const route = useRoute()

const data = reactive({
    form: {
        id: route.params.id,
    }
})

</script>

Guess you like

Origin blog.csdn.net/qq_42759112/article/details/130096900