【问题标题】:Can't toggle state when clicking on component in Vue [duplicate]在Vue中单击组件时无法切换状态[重复]
【发布时间】:2019-09-18 02:47:13
【问题描述】:

我试图在单击特定元素时切换状态

<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>

我只想将点击事件粘贴到箭头切换器组件而不是整个文本

【问题讨论】:

标签: vue.js conditional-statements state dom-events


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    您应该使用computed 属性观看节目内容:

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

    【讨论】:

      猜你喜欢
      • 2020-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-26
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      • 2021-01-11
      相关资源
      最近更新 更多