Reputation: 127
I've been trying to use document.getElementById("hoge").style.color in watch section but it doesn't work fine. The code below gets executed with selected_title_color1 gets changed and then, adds titleColor1 into p-modal's style. I'm sure titleColor1 gets value as I want but document.getElementById("p-modal").style.color = titleColor1 looks no working.
data () {
return {
colors:['紅色','藍色','黃色','粉色','土地色','水藍色','灰色','淺綠色','橙色'],
colors_dic:{紅色:'red',藍色:'blue',黃色:'yellow',粉色:'pink',土地色:'blawn',水藍色:'aqua',灰色:'gray',淺綠色:'palegreen',橙色:'orange'},
selected_title_color1:'',
}
}
watch:{
selected_title_color1: function () {
var titleColor0 = this.selected_title_color1;
var titleColor1 = this.colors_dic[titleColor0];
console.log(titleColor1)
document.getElementById("p-modal").style.color = titleColor1
}
},
Upvotes: 1
Views: 790
Reputation: 4506
You could use the Class and Style Bindings to achieve this as follows:
new Vue({
el: "#app",
data() {
return {
colors: ['紅色', '藍色', '黃色', '粉色', '土地色', '水藍色', '灰色', '淺綠色', '橙色'],
colors_dic: {
紅色: 'red',
藍色: 'blue',
黃色: 'yellow',
粉色: 'pink',
土地色: 'blawn',
水藍色: 'aqua',
灰色: 'gray',
淺綠色: 'palegreen',
橙色: 'orange'
},
selected_title_color1: '',
titleColor1: '',
}
},
watch: {
selected_title_color1: function() {
this.titleColor1 = this.colors_dic[this.selected_title_color1];
}
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
Select Color:
<select v-model="selected_title_color1">
<option v-for="color in colors" :value="color">{{color}}</option>
</select>
<br/><br/>
<span :style="{ color : titleColor1 }">Toggle the dropdown to change the text color...</span>
</div>
Upvotes: 3
Reputation: 326
You should use "ref" for accessing to dom element in Vue:
<template>
<div>
<div ref="test">
test
</div>
</div>
</template>
<script>
export default {
name: 'Test',
data () {
return {
test: 'test'
}
},
watch: {
test () {
const colors = [
'red',
'green',
'blue',
'purple',
'pink'
]
this.$refs.test.style.color = colors[Math.floor(Math.random() * colors.length)]
}
}
}
</script>
Upvotes: 0