Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

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

vue 使用v-if时有什么办法只让mounted钩子 只在第一次创建时候执行 之后都不执行吗

期望实现:

父组件的点击事件里 反复创建销毁<child>子组件时,子组件的mounted只执行一次

(不能使用 v-show 因为首次进入页面的时候 必须通过点击事件触发)

父组件

<button @click="click"><button>
<child v-if="show"></child>
data() {
    return {
        show:false
    }
},
methods:{
    click(){
       this.show = !this.show;
    }
}

子组件

<template></template>
<script>
    export default {
        methods: {
            request() {
                一个axios请求函数
            }
        },
        mounted(){
        //执行这个请求
            this.request();
        }
    }
</script>

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

1 Answer

0 votes
by (71.8m points)

1.不太好看的做法
使用两个变量:显示标记show,点击标记click。v-show="show" v-if="click"

clickBtn () {
  this.click = true
  this.show = !this.show
}

2.使用keep-alive组件 ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...