背景: 后管系统配置一个产品后, 前端 (vue.js 框架) 取到这些产品信息并展示出来, 产品经理要求在文本内容中添加链接.
例如:
本保险不承保前往处于战争状态或已被宣布为紧急状态的国家或地区, 最新信息以登陆 < a href="javascript:void(0)" style="color: rgb(55, 105, 252);">http://baoxian.pingan.com/dangerous_zone/war.shtml</a > 的查询结果为准.
如果上面内容中是简单的链接跳转, 用 v-HTML 把上面段内容展示出来即可.
问题关键是, 不仅仅是简单的链接, 还要有一些逻辑判断, 所以要用 "动态添加 dom 元素, 并绑定 vue 事件"
解决办法一:
因为 VUE 是先编译, 后执行, 所以元素上的方法要预先绑定.
这是我们定义的 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();
- // 一些复杂的逻辑判断
- myApp.doLink(urlStr); // 调用 myApp 的方法
- }
- }
- });
- var myApp= new Vue({
- el: "#app",
- data: {
- book: null
- },
- mounted () {
- var component = new periodDiv().$mount(); // 每次添加需要重新 new 一个
- var $dom = $(component.$el); // 获取动态元素的 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()})
- }
- }
- }
- });
这个方法感觉有点麻烦, 后面又找到一个超级简单的方法,
解决办法二:
- var myApp= new Vue({
- el: "#app",
- data: {
- book: null
- },
- mounted () {
- this.$nextTick(() => {
- // 动态添加 dom 元素, 并绑定 VUE 事件(打开 PDF)(.PDF-item 为动态添加的元素, 放置在父元素. 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()})
- }
- }
- }
这对产品内容配置有一定要求:
<span class="pdf-body">本保险不承保前往处于战争状态或已被宣布为紧急状态的国家或地区, 最新信息以登陆 < span class="pdf-item" PDF-title="xxx" PDF-url="http://baoxian.pingan.com/dangerous_zone/war.shtml" style="color: rgb(55, 105, 252);">战争状态地区</span > 的查询结果为准.</span>
来源: http://www.jianshu.com/p/fed288ea9aba