1

如果我尝试使用两个<div>'s 的一个非常简单的示例,使用 一次只显示其中一个v-if,则out-in过渡不会在它们之间消失。

<div id="app">
  <transition name="fade" mode="out-in">
    <div v-if="(box==='a')">a</div>
    <div v-if="(box==='b')">b</div>
  </transition>

  <button @click="box='a'">show a</button>
  <button @click="box='b'">show b</button>
</div>

还有我的动画CSS代码:

.fade-enter-active, .fade-leave-active {
    transition: opacity .3s ease;
}
.fade-enter, .fade-leave-to {
    opacity: 0;
}

JSFiddle 位于此处:https ://jsfiddle.net/3ckto1am/1/

4

1 回答 1

0

您可以将“div box”设置为一个boolean,然后创建一个方法来切换,boolean如下true/false所示:

模板:

<div id="app">
  <transition name="fade" mode="out-in">
    <div v-if="boxA" key="boxA">Div A</div>
    <div v-else key="boxB">Div B</div>
  </transition>

  <button @click="toggleBoxes">Toggle div boxes!</button>
</div>

JavaScript:

new Vue({
  el: "#app",
  data: {
    boxA: true
  },
  methods: {
    toggleBoxes() {
        this.boxA = !this.boxA;
    }
  }
})

编辑:

As for the <transition>, when toggling between elements that have the same tag name, you must tell Vue that they are distinct elements by giving them unique key attributes (key='<uniqueKey>') to the tag elements, you can read about it here.

You can check this working code sample.

However, if you still want to have two buttons to toggle the <div>, check this code instead.

Furthermore, I highly suggest you to read the official documentation on Conditional Rendering with Vuejs.

于 2019-10-01T18:12:13.990 回答