v-html中使用filters
阿新 • • 發佈:2019-02-10
Vue2.0的過濾器只能應用在{{ }}和v-bind中,不再支援v-html中使用,如果要在v-html中使用過濾器,怎麼辦呢?
解決方法有三種:
1、使用全域性方法
定義方法
methods: { formatTrend(val) { let trend = 'up'; if(val.indexOf('-') > -1){ trend = 'down'; val = val.substr(1); } return `<i class="trend ${trend}"></i>${val}`; } }
呼叫方法
<span v-html="formatTrend(value)"></span>
2、使用computed屬性,當監聽到資料發生變化的時候,會立即執行計算,並返回結果
定義原變數
data() {
return {
trendText: ''
}
}
定義計算後的變數
computed: { trendHtml: function () { let trend = 'up' ,val = this.trendText; if(val.indexOf('-') > -1){ trend = 'down'; val = val.substr(1); } return `<i class="trend ${trend}"></i>${val}`; }
顯示變數
<span v-html="trendHtml"></span>
3、使用$options.filters
定義filter
formatTrend(val) { let trend = 'up'; if(val.indexOf('-') > -1){ trend = 'down'; val = val.substr(1); } return `<i class="trend ${trend}"></i>${val}`; } export default { formatTrend }
引入filter
import { formatTrend } from '../../utils/filter.js'
呼叫filter
<span v-html="$options.filters.formatTrend(value)"></span>