原型正在返回我的函数,而不是返回值

时间:2020-02-08 00:54:38

标签: javascript vue.js prototype

我想创建与图片相似的页面的字幕 enter image description here

我想通过从main.js调用我的原型来做到这一点

Vue.prototype.subtitlePage = function () {
  var path = this.$route.path;
  var array_path = path.split('/');
  var subtitle = "<ul class='subtitle'>";
  var index;
  for (index = 1; index < array_path.length - 2; index++) {
    subtitle += "<li>" + array_path[index] + "</li> >>";
  }
  subtitle += "<li>" + array_path[index] + "</li><ul>";
  return subtitle;
}

我在构造屏幕时会这样调用函数

<p class="indextitle">Subir Nova Redação</p>
<p v-html="subtitlePage"></p>

但是,屏幕上显示的文本不是函数中装载的html返回,而是函数的代码

function () { var path = this.$route.path; var array_path = path.split('/'); var subtitle = "
"; var index; for (index = 1; index < array_path.length - 2; index++) { subtitle += "
" + array_path[index] + "
>>"; } subtitle += "
" + array_path[index] + "
"; return subtitle; }

有人知道我在做什么错吗,我必须在代码中进行哪些更改才能显示在字幕中,该字幕是我在函数中设置的?

2 个答案:

答案 0 :(得分:1)

v-html expects a string,在给定函数的同时,会产生字符串化的函数输出。应该是:

// Get all Users
func allUser (completion: @escaping ([UserModel]) -> Void) {

    let dispatchGroup = DispatchGroup()
    var model = [UserModel]()

    let db = Firestore.firestore()
    let docRef = db.collection("users")
    docRef.getDocuments { (querySnapshot, err) in

        for document in querySnapshot!.documents {
            dispatchGroup.enter()
            print("disp enter")
            let dic = document.data()
            model.append(UserModel(dictionary: dic))
            dispatchGroup.leave()
            print("disp leave")
        }
    }
    dispatchGroup.notify(queue: .main) {
        completion(model)
        print("completion")
    }
}

在实践中,切勿使用用户定义的数据来完成此操作。

在网站上动态呈现任意HTML可能非常危险,因为它很容易导致XSS攻击。只能在受信任的内容上使用v-html,而不能在用户提供的内容上使用。

URL是用户定义的数据。罪魁祸首可以对其进行定制,以评估用户端的任意JS。

正确的方法是为面包屑创建一个组件,并使用以下命令将其输出:

<p v-html="subtitlePage()"></p>

如果一个段可能包含URL编码的符号(在此示例中为空格和非ASCII字符),则段需要另外用<li v-for="pathSegment in pathSegments">{{pathSegment}}</li> 进行转换(原始代码中未涉及,它将是一个decodeURIComponent的主要危害。

答案 1 :(得分:0)

我设法做到了

Vue.mixin({
  computed: {
    subtitlePage: {
      get: function () {
        var path = this.$route.path;
        var array_path = path.split('/');
        var subtitle = "<ul class='subtitle'>";
        var index;
        for (index = 1; index < array_path.length - 2; index++) {
          subtitle += "<li>" + array_path[index] + "</li> >>";
        }
        subtitle += "<li>" + array_path[index] + "</li><ul>";
        return subtitle; 
      }
    }
  }
})