单击时更改生成的 div 的样式属性
Change style attribute of a generated div on click
我正在使用 vue-cli,我遇到了一个问题。
我有一排 24 div 是这样生成的:
<template>
<div class="row">
<div class="hour" v-on:click="colorize" v-for="n in 24"></div>
</div>
</template>
我正在尝试根据 VueX 商店中保存的值更改单击 hour
div 的背景颜色,但这不是重要部分
这是我的方法:
methods: {
colorize() {
if(this.$store.state.picked === 1) {
this.style.backgroundColor="rgb(103, 103, 103)";
}
}
}
商店有效,问题来自 'this' 属性,我认为我使用错误。
有什么建议吗? :)
this
指的是 Vue 实例而不是被点击的元素,所以你应该这样做:
methods: {
colorize(event) {
if(this.$store.state.picked === 1) {
event.target.style.backgroundColor="rgb(103, 103, 103)";
}
}
}
new Vue({
el: '#app',
data() {
return {
elements: [
{content:'content 1',tooltip:'tool tip 1'},
{content:'content 2',tooltip:'tool tip 2'},
{content:'content 3',tooltip:'tool tip 3'},
{content:'content 4',tooltip:'tool tip 4'},
]
}
}
, methods: {
colorize(event) {
event.target.style.backgroundColor="rgb(103, 103, 103)";
}
}
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app" data-app>
<div class="row">
<div class="hour" v-on:click="colorize" v-for="n in elements">
{{n.content}}
</div>
</div>
</div>
我正在使用 vue-cli,我遇到了一个问题。
我有一排 24 div 是这样生成的:
<template>
<div class="row">
<div class="hour" v-on:click="colorize" v-for="n in 24"></div>
</div>
</template>
我正在尝试根据 VueX 商店中保存的值更改单击 hour
div 的背景颜色,但这不是重要部分
这是我的方法:
methods: {
colorize() {
if(this.$store.state.picked === 1) {
this.style.backgroundColor="rgb(103, 103, 103)";
}
}
}
商店有效,问题来自 'this' 属性,我认为我使用错误。
有什么建议吗? :)
this
指的是 Vue 实例而不是被点击的元素,所以你应该这样做:
methods: {
colorize(event) {
if(this.$store.state.picked === 1) {
event.target.style.backgroundColor="rgb(103, 103, 103)";
}
}
}
new Vue({
el: '#app',
data() {
return {
elements: [
{content:'content 1',tooltip:'tool tip 1'},
{content:'content 2',tooltip:'tool tip 2'},
{content:'content 3',tooltip:'tool tip 3'},
{content:'content 4',tooltip:'tool tip 4'},
]
}
}
, methods: {
colorize(event) {
event.target.style.backgroundColor="rgb(103, 103, 103)";
}
}
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app" data-app>
<div class="row">
<div class="hour" v-on:click="colorize" v-for="n in elements">
{{n.content}}
</div>
</div>
</div>