在Vue中,无论如何在模板中绑定属性时引用元素?

时间:2018-06-04 04:59:28

标签: vuejs2

在模板范围内,是否存在引用元素本身的变量,如$ this或$ el?

而不是,

<template>
    <div @click="$emit('xxx')" :class="{active:mode=='xxx'}" something_for_xxx></div>
    <div @click="$emit('yyy')" :class="{active:mode=='yyy'}" something_for_yyy></div>
    <div @click="$emit('zzz')" :class="{active:mode=='zzz'}" something_for_zzz></div>
</template>

我们可以编写类似下面的内容,以避免忘记更改其中一个模式名称吗?

<template>
    <div mode="xxx" @click="$emit($this.mode)" :class="{active:mode==$this.mode}" something_for_xxx></div>
    <div mode="yyy" @click="$emit($this.mode)" :class="{active:mode==$this.mode}" something_for_yyy></div>
    <div mode="zzz" @click="$emit($this.mode)" :class="{active:mode==$this.mode}" something_for_zzz></div>
</template>

解决方法:

<template>
    <div v-for"mode_ in ["xxx"] @click="$emit(mode_)" :class="{active:mode==mode_}" something_for_xxx></div>
    <div v-for"mode_ in ["yyy"] @click="$emit(mode_)" :class="{active:mode==mode_}" something_for_yyy></div>
    <div v-for"mode_ in ["zzz"] @click="$emit(mode_)" :class="{active:mode==mode_}" something_for_zzz></div>
</template>

2 个答案:

答案 0 :(得分:0)

这是您应该在v-for循环中构建元素的典型情况:

&#13;
&#13;
Vue.component('my-component', {
  template: '#my-component',
  props: {
    mode: String,
  },
  data() {
    return {
      modes: ['xxx', 'yyy', 'zzz'],
    };
  },
});

new Vue({
  el: '#app',
  data: {
    mode: 'xxx',
  },
  methods: {
    log(event) {
      this.mode = event;
      console.log(event);
    }
  },
});
&#13;
.active {
  color: green;
}

.pointer {
  cursor: pointer;
}
&#13;
<script src="https://unpkg.com/vue@2"></script>

<div id="app">
  <my-component
      :mode='mode'
      @click="log($event)"
  ></my-component>
</div>

<template id="my-component">
  <div>
    <div
        v-for="currentMode of modes"
        @click="$emit('click', currentMode)"
        :class="{active:mode==currentMode}"
        class="pointer"
    >{{currentMode}}</div>
  </div>
</template>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

在事件处理程序中,您始终可以访问$event.target来访问元素(请参阅https://vuejs.org/v2/guide/events.html#Method-Event-Handlers),但是对于内联绑定(如:class),您不能,因为元素尚未呈现爱好。

我建议您更改每个值的循环方式

<div v-for="elMode in ['xxx', 'yyy', 'zzz']"
     @click="$emit('click', elMode)" :class="{active:mode==elMode}"/>