我有一个输入(右上角),用户可以在其中搜索内容,当它的指令长度达到 3 个字符时,它将显示产品列表并突出显示匹配...
看看我的代码:
html
<div id="app">
<div id="header">
<div class="right"><input type="text" v-model="message" v-on:keyup="searchStart()" v-on:blur="searchLeave()"/>
<ul v-if="this.searchInput" class="product-list">
<li v-for="product in products">
{{ product.id }} - {{ product.name | highlight }} - {{ product.qtd }}</li></ul>
</div>
</div>
<div id="main">
<div id="menu">fdfds</div>
<div id="container">{{ message }}</div>
</div>
</div>
js
var search = new Vue({
el: "#app",
data: {
message: "",
searchInput: false,
products: [
{
id: 1,
name: "produto 01",
qtd: 20
},
{
id: 2,
name: "produto 02",
qtd: 40
},
{
id: 3,
name: "produto 03",
qtd: 30
},
]
},
methods: {
searchStart: function(){
if(this.message.length >= 3)
this.searchInput = true;
console.log(this.searchInput);
},
searchLeave: function(){
this.searchInput = false;
this.message = "";
console.log(this.searchInput);
}
},
filters: {
highlight: function(value){
return value.replace(search.message, '<span class=\'highlight\'>' + search.message + '</span>');
}
}
});
在这里你可以看到一个活笔:http://codepen.io/caiokawasaki/pen/dXaPyj
尝试在笔内输入prod
...
我的过滤器是否正确?我创建过滤器的方式是否正确?
主要问题是:如何从我的过滤器中输出 HTML?
编辑/解决方案
案例中的问题是 codepen
,与 vue
有某种冲突,所以我无法使用 {{{ 转义 html }}}
,将代码放入另一个编辑器 (jsfidle) 中,它可以正常工作。
我接受奖励的答案,因为它是正确的。
最佳答案
在这里你需要 3 个步骤来实现你想要的:
- 使用三大括号{{{ }}} 显示未转义的html
- 通过 v-model 变量过滤您的用户,以便仅显示匹配项
- 用
<span>
替换匹配的子串标签
查看计算属性 filteredUsers
和这个工作中的过滤器 jsfiddle
关于javascript - 如何从 mustache 内的过滤器输出 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38925579/