用Vue动态替换字符串的一部分

时间:2018-08-08 14:28:59

标签: javascript vue.js

我正在尝试解决一个问题。

我有一个基本上是HTML代码的字符串:

let htmlTitle = "<a href="/news/sky-sport-hd-in-italia-dal-18-novembr">Sky Sport HD in italia dal 18 novembre</a> | <a href="/news/ecco-il-genio-spagnolo-designer-di-moto-elettriche">News</a> | <a href="/news/lg-electronic-e-here-insieme-per-l-auto-connessa-e-autonoma">News</a>"

该字符串来自我的数据库。

我的Vue应用程序中有一个“子弹”输入字段,并且在子弹中有:

 "sky-sport-hd-in-italia-dal-18-novembr"

这是字符串引用的第一个内容的固定链接。

当我更改输入字段时,我需要标题字符串适应我的更改,而我不知道该怎么做。

在标题字符串中,我可以有无限数量的锚标记,但是我只需要更改与子段匹配的href值即可。

我需要这样的东西:

"<a href="{{ slug }}">Sky Sport HD in italia dal 18 novembre</a> | <a href="/news/ecco-il-genio-spagnolo-designer-di-moto-elettriche">News</a> | <a href="/news/lg-electronic-e-here-insieme-per-l-auto-connessa-e-autonoma">News</a>"

我可以使用计算所得的值,但是可以使用Wysiwyg编辑器编辑字符串,在其中可以更改标题(“ Ital dal 18 novembre中的Sky Sport HD”或“ News”)。我只需要保持弹头对齐...

2 个答案:

答案 0 :(得分:0)

我想说的是,您需要使用计算值(promise api)。

字符串htmlTitle将会是计算值

computed: {
    // ES6
    htmlTitle () {
        return `<a href="${this.slug}">Sky Sport HD in italia dal 18 novembre</a> | <a href="/news/ecco-il-genio-spagnolo-designer-di-moto-elettriche">News</a> | <a href="/news/lg-electronic-e-here-insieme-per-l-auto-connessa-e-autonoma">News</a>`
    }

    // ES5
    htmlTitle: funciton() {
        return "<a href='" + this.slug + "'>Sky Sport HD in italia dal 18 novembre</a> | <a href="/news/ecco-il-genio-spagnolo-designer-di-moto-elettriche">News</a> | <a href="/news/lg-electronic-e-here-insieme-per-l-auto-connessa-e-autonoma">News</a>"
    }
}

答案 1 :(得分:0)

使用观察者和v-html。当您更改子弹时-只需使用链接更新变量 这是一个示例

watch: {
  slug: function(val) {
    this.href = this.result;
  }
}

https://jsfiddle.net/1b68eLdr/52554/

相关问题