Vue同一个类div,仅扩展子级,不扩展(此)父级

时间:2018-10-12 10:48:26

标签: javascript jquery vue.js

所有孩子和父母div都属于同一班。我附加了v-on:click方法来仅切换所单击的父级之一中的子级,而不切换所有子级。如果我添加(此)方法无效。谢谢。

        <div class="expand-box" v-on:click="textToggle()">
            <div class="expand-title">Lorem ipsum</div>
            <div class="expand-text">Child</div>
        </div>
        <div class="expand-box" v-on:click="textToggle()">
            <div class="expand-title">Lorem Ipsum</div>
            <span class="expand-text">Child.</span>
        </div>



mounted(){
      this.hideText();
},

methods: {
      hideText: function() {
        $(".expand-text").hide();
      },
      textToggle: function() {
        $(".expand-text").toggle(300);
      }
  }

2 个答案:

答案 0 :(得分:3)

首先,当您使用v-on:click时,如果不传递参数,则需要设置函数名称,例如v-on:click="textToggle"

不建议将jQuery alond Vuejs用于动画和dom操作, 您需要使用CSS或Vuejs动画:

.msg {
    transition: all .3s ease;
    height: 30px;
    padding: 10px;
    background-color: #eee;
    overflow: hidden;
}
.msg.v-enter, .msg.v-leave {
    height: 0;
    padding: 0 10px;
    opacity: 0;
}
<p class="msg" v-if="show" v-transition>Hello!</p>

答案 1 :(得分:1)

您可以将$event作为textToggle的参数进行传递,以使其变为v-on:click="textToggle($event)",然后您的方法将使用此引用来使用来切换该元素,

textToggle: function(elem) {
  $(elem.target).toggle(300);
}

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!'
  },
  mounted() {
    this.hideText();
  },

  methods: {
    hideText: function() {
      $(".expand-text").hide();
    },
    textToggle: function(elem) {
      $(elem.target).toggle(300);
    }
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://unpkg.com/vue"></script>
<div id='app'>
  <div class="expand-box" v-on:click="textToggle($event)">
    <div class="expand-title">Lorem ipsum</div>
    <div class="expand-text">Child</div>
  </div>
  <div class="expand-box" v-on:click="textToggle($event)">
    <div class="expand-title">Lorem Ipsum</div>
    <span class="expand-text">Child.</span>
  </div>
</div>

您还可以在HTML元素中使用ref来获取该元素的引用,例如:

HTML

<div class="expand-box" v-on:click="textToggle('el1')" ref="el1">
    <div class="expand-title">Lorem ipsum</div>
    <div class="expand-text">Child</div>
</div>
<div class="expand-box" v-on:click="textToggle('el2')" ref="el2">
    <div class="expand-title">Lorem Ipsum</div>
    <span class="expand-text">Child.</span>
</div>

方法

textToggle: function(refId) {
  this.$refs[refId].toggle(300);
}