在单页应用中加入Disqus

今天将主题hole用Vue.js重写了下,一路下来挺顺利的,但在加入评论系统(Disqus)的时候遇到了一点问题。Disqus只能第一次载入时显示一次,以后就无法显示了。后来,在查阅Vue.js文档时,发现一个directive就可以轻松解决这个问题。。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var Vue = require('vue');
Vue.directive('show-comment',{
bind:function(){
(function(){
var d = document,
s = d.createElement('script');
s.id = 'disqus';
s.src = '//bitibiti.disqus.com/embed.js'; //你的embed.js
s.setAttribute('data-timestamp',+new Date());
(d.head || d.body).appendChild(s);
})();
},
update:function(newValue,oldValue){
var disqus_config = function(){
this.page.url = newValue.url; //你的文章url
this.page.identifier = newValue.id; //文章id
}
},
unbind:function(){
var dis = document.getElementById('disqus');
dis.parentNode.removeChild(dis);
}
});


2016/3/19更新
上述方法存在错误,虽然能够成功显示disqus,但评论数据显示不正确。根据官方文档,更正如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 在首页引入embed.js
<script type="text/javascript" src="//bitibiti.disqus.com/embed.js"></script>

// 自定义directive
Vue.directive('show-comment',{
update: function(newValue,oldValue) {
if(newVaule.id) {
DISQUS.reset({
reload: true;
config: function() {
this.page.identifier = newValue.id;
this.page.url = location.href;
}
});
}
}
});