如何添加 JSON 中提到的'click'事件侦听器或访问'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>

以下是我对所问问题的回答。我没有弄清楚如何使@click="myFun('myData')"工作,而是使用了data-image="myData"

<template lang="pug">
div(ref="cars")
.row.no-gutters(v-for="(item, index) in cars" :key="index")
p(v-html="item.desc")
</template>
<script>
export default {
data() {
return {
cars: [
{
id: 1,
desc: 'Some text about <a href="#" onClick="return false;" class="jsOpenImgModal" data-image="/images/dash.png">dash</a> lorem ipsum continues.',
}, {
id: 2,
desc: 'Description without link',
}, {
id: 3,
desc: 'And, Some text about <a href="#" onClick="return false;" class="jsOpenImgModal" data-image="/image/front.png">front</a> lorem ipsum continues.',
},
],
};
},
mounted() {
const imgModals = this.$refs.cars.querySelectorAll('.jsOpenImgModal');
Object.keys(imgModals).forEach((i) => {
const imgUrl = imgModals[i].dataset.image;
imgModals[i].addEventListener('click', () => this.fnImgModals(imgUrl));
});
},
methods: {
fnImgModals(imgUrl) {
console.log('dataset.image :>> ', imgUrl);
},
},
};
</script>

注意:你们中很少有人会觉得这似乎是不现实的情况任何开发人员都可能遇到。我创建的cars数据以上只是为了证明我需要什么,但我实际上需要这个更复杂的数据和实际项目的解决方案。

最新更新