【问题标题】:Creating/Destroying the Vue Component based on text search基于文本搜索创建/销毁 Vue 组件
【发布时间】:2019-02-20 12:12:27
【问题描述】:

我在App.vue中有以下内容

<template>
    <div id="app">
        <input type="text" v-model="term">
        <hello-world text="Button 1" v-if="term === ''"></hello-world>
        <hello-world v-else text="Button 2"></hello-world>
    </div>
</template>

<script>
import HelloWorld from '@/components/HelloWorld'

export default {
    name: 'app',
    data() {
        return {
            term: ''
        }
    },
    components: {
        HelloWorld
    }
}
</script>

这是HelloWorld.vue

<template>
    <div>
        <button>{{ text }}</button>
    </div>
</template>

<script>
export default {
    props: {
        text: String
    },
    created() {
        console.log('Created')
    },
    destroyed() {
        console.log('Destroyed')
    }
}
</script>

所以,当我输入内容时,第一个组件应该被销毁,而第二个组件应该被创建。但是,不会发生这样的事情。组件既不会被销毁也不会被创建。

好像v-if 没有触发created() & destroyed() 函数。请帮我解决这个问题。

【问题讨论】:

  • 您可以尝试使用mounted() 挂钩,而只使用v-if="term" 吗?

标签: javascript vue.js components


【解决方案1】:

Vue 使用虚拟 dom 方法。因此,它是在比较虚拟树,而不是识别结构的变化(oldNode.type === newNode.type)。当它发生时,Vue 会更新相同的组件,而不是销毁旧节点并创建一个新节点。

尝试强制 Vue 检测虚拟树更改,避免使用具有相同标签名称并由 v-if 指令控制的兄弟姐妹。

参考:

https://medium.com/@deathmood/how-to-write-your-own-virtual-dom-ee74acc13060

Vue.component('hello-world', {
  props: {
    text: String
  },
  created() {
    console.log('Created')
  },
  destroyed() {
    console.log('Destroyed')
  },
  template: "<button>{{ text }}</button>"
});

var app = new Vue({
  el: "#app",
  data() {
    return {
      term: ''
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <input type="text" v-model="term">
  <span><hello-world v-if="!term" text="Button 1"></hello-world></span>
  <span><hello-world v-if="term" text="Button 2"></hello-world></span>
</div>

【讨论】:

    【解决方案2】:

    我不确定您要实现什么,但测试您从两个组件创建的代码日志 https://codesandbox.io/s/8l0j43zy89 由于您实际上是有条件地显示相同的组件,因此我认为它不会被破坏。

    【讨论】:

      猜你喜欢
      • 2019-12-04
      • 2020-09-24
      • 2019-08-25
      • 2013-07-12
      • 2017-10-26
      • 1970-01-01
      • 1970-01-01
      • 2019-02-18
      • 1970-01-01
      相关资源
      最近更新 更多