单击Vue中的组件时无法显示状态

时间:2019-04-29 13:03:06

标签: vue.js javascript-events conditional state

当我单击特定元素时,我试图改变状态

<script>
import ArrowSwitcher from '@/components/ui/ArrowSwitcher.vue'

export default {
  components: {
    ArrowSwitcher
  },
  data () {
    return {
      showContent: false
    }
  },
  methods: {
    switcher () {
      this.showContent = !this.showContent
    }
  }
}
</script>
<span class='targeting-global__name' @click='switcher'>
Some Text
    <ArrowSwitcher :showContent='showContent'/>
  </span>

当我在父元素(只是html,而不是其他组件)上粘贴事件时,

令人惊讶的是,这种方法根本不会改变状态! 为什么?

<span class='targeting-global__name'>
    Targeting Global
    <ArrowSwitcher :showContent='showContent' @click='switcher'/>
  </span>

我想仅将点击事件保留在Arrow switcher组件上,而不是整个文本

2 个答案:

答案 0 :(得分:1)

要在组件上绑定本机事件,您必须使用以下语法:

<ArrowSwitcher :showContent='showContent' @click.native='switcher'/>

以下是文档:https://vuejs.org/v2/guide/components-custom-events.html#Binding-Native-Events-to-Components

答案 1 :(得分:1)

您应该使用computed属性观看showContent:

export default {
...,
computed: {
  showContent: function () {
    return showContent
  }
}