首页 > 解决方案 > 如何添加“click”事件侦听器或访问 JSON 中提到的“ref”

问题描述

这是我的数据,看起来像这样:

cars: [
  {
    id: 1,
    desc: 'Description with <a ref="id1" @click="openModel('my-car')">a link</a> lorem ipsum continues.'
  }, {
    id: 2,
    desc: 'Description without link'
  }, {
    id: 3,
    desc: 'Description with <a ref="id3" @click="openAnotherModel('my-dashboard')">a link</a> lorem ipsum continues.'
  }
]

在我的模板中,我可以这样做:

<p v-for="item in cars" v-html="item"></p>

当然,这肯定行不通:

<p v-for="item in cars">{{ item }}</p>

如何访问在我的 vue 实例中定义的方法/函数:

methods: {
  openModel(str) {
    console.log('openModel :>> ', str);
  },
  openAnotherModel(str) {
    console.log('openAnotherModel :>> ', str);
  },
},

标签: javascriptjsonvue.jsvuejs2

解决方案


评论后编辑。

您可以像这样从已安装的事件挂钩访问您的链接。

new Vue({
  el: "#app",
  data: {
    cars: [
      {
        id: 1,
        desc: `Description with <a href="my-car">a link</a> lorem ipsum continues.`
      }, {
        id: 2,
        desc: `Description without link`
      }, {
        id: 3,
        desc: `Description with <a href="dash-board">a link</a> lorem ipsum continues.`
      }
    ]
  },
  methods: {
    dispatchLink(e){
      e.preventDefault();
      const target = e.target;
      const str = target.getAttribute('href');
      
      switch(str) {
          case 'my-car':
            this.openModel(str)
            break;
          case 'dash-board':
            this.openAnotherModel(str)
            break;
          // other link type ...
        }
    },
    openModel(str) {
      console.log('openModel :>> ', str);
    },
    openAnotherModel(str) {
      console.log('openAnotherModel :>> ', str);
    }
  },
  mounted(){
      const carsLinks = this.$el.querySelectorAll('p a');
      carsLinks.forEach(link => link.addEventListener('click', this.dispatchLink)       
      )
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <p 
    v-for="car in cars" 
    :key="car.id" 
    v-html="car.desc"
    :id="car.id"
  >
  </p>
</div>


推荐阅读