Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

vue.js - Component stays visible when using props in composition API

I have a vue 3 app which display product information. The home component displays all available products. Each of them has a button which takes me to a component displaying information about said product called Single Box. It gets the product ID from the route params and then fetches additional information via graphql. It looks like this:

<template>
<BoxDisplay :box="box"></BoxDisplay>
</template>

<script>
import { useQuery, useResult } from '@vue/apollo-composable';
import { useRoute } from 'vue-router'
import singleBoxQuery from '../graphql/singleBox.query.gql'
import BoxDisplay from '../components/BoxDisplay'

export default {
    components: {
        BoxDisplay
    },
    setup() {
        const route = useRoute();
        const boxId = route.params.id
        const {result } = useQuery(singleBoxQuery, {id: boxId})
        const box = useResult(result, null)
        return {
            boxId,
            box
        }
    }
}
</script>

The BoxDisplay component is then used to show the infos of the current box. There is going to be more going on this page later so the BoxDisplay is needed. It looks like this:

<template>
<div class="p-d-flex p-jc-center">
    <div v-if="box">
        <h1>{{box.Name}}</h1>
        <div v-html="myhtml"></div>
    </div>
    <div v-else>
        <ProgressSpinner />
    </div>
    </div>
</template>

<script>

export default {
    props: {
        box: {}
    },
    setup(props){
        const myhtml = "<h1>hello</h1>" + props.box.Name
        return {
            myhtml
        }
    }
}
</script>

The problem is now, that as soon as I use props in setup() the component stay visible when I click back in my browser. It stays there until I refresh the page. What am I doing wrong?

question from:https://stackoverflow.com/questions/65937858/component-stays-visible-when-using-props-in-composition-api

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Use ref and computed

https://v3.vuejs.org/guide/composition-api-introduction.html#reactive-variables-with-ref

```

import { ref, computed } from 'vue'
```

const myhtml = computed(() => '<h1>hello</h1>' + props.box.Name)

or

const myhtml = ref('<h1>hello</h1>' + props.box.Name)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...