背景:后管系統(tǒng)配置一個產(chǎn)品后,前端(vue.js框架)取到這些產(chǎn)品信息并展示出來,產(chǎn)品經(jīng)理要求在文本內(nèi)容中添加鏈接。
例如:
本保險(xiǎn)不承保前往處于戰(zhàn)爭狀態(tài)或已被宣布為緊急狀態(tài)的國家或地區(qū),最新信息以登陸<a href="javascript:void(0)" style="color: rgb(55, 105, 252);">http://baoxian.pingan.com/dangerous_zone/war.shtml</a>的查詢結(jié)果為準(zhǔn)。
如果上面內(nèi)容中是簡單的鏈接跳轉(zhuǎn),用v-html把上面段內(nèi)容展示出來即可。
問題關(guān)鍵是,不僅僅是簡單的鏈接,還要有一些邏輯判斷,所以要用“動態(tài)添加dom元素,并綁定vue事件”
解決辦法一:
因?yàn)閂UE是先編譯,后執(zhí)行,所以元素上的方法要預(yù)先綁定。
這是我們定義的VUE組件,放在最外層:
var periodDiv = Vue.extend({
template: "<div @click='toLink($event);' class='class-item' data-url='http://baoxian.pingan.com/dangerous_zone/war.shtml'>" +
"Available" +
"</div>",
methods: {
toLink: function ($event) {
var urlStr = $event.target.getAttribute("data-url").trim();
// 一些復(fù)雜的邏輯判斷
myApp.doLink(urlStr); // 調(diào)用myApp的方法
}
}
});
var myApp= new Vue({
el: "#app",
data: {
book: null
},
mounted () {
var component = new periodDiv().$mount(); // 每次添加需要重新new一個
var $dom = $(component.$el); // 獲取動態(tài)元素的jquery對象
},
methods: {
doLink: function (url) {
openPdf(url);
},
openPdf () {
let attributes = e.target.getAttributeNames()
if (attributes.includes('pdf-title') && attributes.includes('pdf-url')) {
common.openPDF({title: e.target.getAttribute('pdf-title').trim(), file: e.target.getAttribute('pdf-url').trim()})
}
}
}
});
這個方法感覺有點(diǎn)麻煩,后面又找到一個超級簡單的方法,
解決辦法二:
var myApp= new Vue({
el: "#app",
data: {
book: null
},
mounted () {
this.$nextTick(() => {
// 動態(tài)添加dom元素,并綁定VUE事件(打開pdf)(.pdf-item為動態(tài)添加的元素,放置在父元素.pdf-body下)
$('.pdf-body').on('click', '.pdf-item', this.openPdf)
}
},
methods: {
openPdf () {
let attributes = e.target.getAttributeNames()
if (attributes.includes('pdf-title') && attributes.includes('pdf-url')) {
common.openPDF({title: e.target.getAttribute('pdf-title').trim(), file: e.target.getAttribute('pdf-url').trim()})
}
}
}
這對產(chǎn)品內(nèi)容配置有一定要求:
<span class="pdf-body">本保險(xiǎn)不承保前往處于戰(zhàn)爭狀態(tài)或已被宣布為緊急狀態(tài)的國家或地區(qū),最新信息以登陸<span class="pdf-item" pdf-title="xxx" pdf-url="http://baoxian.pingan.com/dangerous_zone/war.shtml" style="color: rgb(55, 105, 252);">戰(zhàn)爭狀態(tài)地區(qū)</span>的查詢結(jié)果為準(zhǔn)。</span>