javascript - 如何添加“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);
},
},
解决方案
评论后编辑。
您可以像这样从已安装的事件挂钩访问您的链接。
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>
推荐阅读
- python - 请让我知道如何将 GEKKO 参数放入变量中
- python - 在熊猫数据框中就地替换值不适用于 .replace()
- c - 睡眠()导致管道破裂?
- python - Beautiful Soup 4 没有拉下此网页上的所有 html
- java - Android SpeechRecognizer如何使连续?
- java - 使用方法填充二维数组时如何修复数组错误和 ArrayStoreException
- python - 如何使我的第二个循环中的数据保存在 csv 的另一行中
- json - 从Angular中的Json文件中按特定字段获取数据
- php - PHP/MySQL - 用于填充 HTML 表格单元格的嵌套循环
- flutter - Google Play 3 天内自动退款