Javascript 如何在Vue中动态标记DOM元素
我有一个简单的过滤器组件设置,所以当你点击一个按钮时,一个计算值会用过滤数据列表更新UI 我想不出“Vue方式”如何标记或标记已单击的按钮,因此在代码中我可以说“过滤器已打开,请将其关闭” 在jquery中,我会这样做,如果过滤器打开,我可以运行不同的代码Javascript 如何在Vue中动态标记DOM元素,javascript,vue.js,vue-component,Javascript,Vue.js,Vue Component,我有一个简单的过滤器组件设置,所以当你点击一个按钮时,一个计算值会用过滤数据列表更新UI 我想不出“Vue方式”如何标记或标记已单击的按钮,因此在代码中我可以说“过滤器已打开,请将其关闭” 在jquery中,我会这样做,如果过滤器打开,我可以运行不同的代码 $('button').on('click', func(){ $this.addClass('hasFilter')} ) Vue代码段 <button class="button is-info" v-on:click="filt
$('button').on('click', func(){ $this.addClass('hasFilter')} )
Vue代码段
<button class="button is-info" v-on:click="filterCats('Logos')">Logos</button>
<button class="button is-info" v-on:click="filterCats('Print')">Print</button>
computed: {
filteredData: function () {
return this.filteredCats
}
},
methods: {
filterCats: function (cat) {
let items = this.filteredCats
let filterCount = 0
let result = {}
Object.keys(items).forEach(key => {
const item = items[key]
if (item.cat_names.some(cat_names => cat_names === cat)) {
result[key] = item
filterCount++
}
})
event.target.classList.add('active')
this.filteredCats = result
}
},
徽标
印刷品
计算:{
filteredData:函数(){
返回此文件。filteredCats
}
},
方法:{
过滤器cat:功能(cat){
让items=this.filteredCats
设filterCount=0
让结果={}
Object.key(items).forEach(key=>{
常量项=项[键]
if(item.cat\u names.some(cat\u names=>cat\u names==cat)){
结果[键]=项
过滤计数++
}
})
event.target.classList.add('active')
this.filteredCats=结果
}
},
您可以使用过滤的数据
属性来控制它
声明:
data() {
return {
// ...
filtered: false // added this line
}
},
然后单击时更改它:
<button class="button is-info" v-on:click="filterCats('Logos'); filtered = true">Logos</button>
演示:
newvue({
el:“#应用程序”,
数据(){
返回{
过滤测试:{
一:{cat_name:['Logos'],title:{rendered:'one'}},
二:{cat_name:['two'],title:{rendered:'two'},
三:{cat_name:['three'],title:{rendered:'three'}}
},
过滤:false//添加了此行
}
},
计算:{
filteredData:函数(){
返回此文件。filteredCats
}
},
方法:{
过滤器cat:功能(cat){
让items=this.filteredCats
设filterCount=0
让结果={}
Object.key(items).forEach(key=>{
常量项=项[键]
if(item.cat\u names.some(cat\u names=>cat\u names==cat)){
结果[键]=项
过滤计数++
}
})
event.target.classList.add('active')
this.filteredCats=结果
this.filtered=true;//添加了此行
}
},
})
过滤?{{过滤}}
标志
{{asset.title.rendered}
您可以在Vue中的数据
中保留状态,而不是在DOM中跟踪状态,而是在数据
中跟踪状态。当您有多个按钮时,这不起作用,请更新我的代码。谢谢这很有道理,谢谢!但是,如何使用多个按钮?当你过滤一个按钮时,过滤的数据会更新所有内容。你必须为每个按钮创建一个属性。如果愿意,还可以使用索引创建数组和引用。
methods: {
filterCats: function (cat) {
// ...
this.filteredCats = result
this.filtered = true; // added this line
}
},