[英]How do I switch text in a div from 'dark' and 'light' back and forth when i click it in vuejs?
I'm making a page color toggle for my website and I want to change from using two different radio buttons to a div
that you click to toggle the color.我正在为我的网站进行页面颜色切换,我想从使用两个不同的单选按钮更改为单击以切换颜色的div
。 I also need the text in the div
to change:我还需要更改div
中的文本:
var theme = new Vue({
el: '#theme',
data: {
picked: local?.theme || 'default',
},
watch: {
picked: function (val) {
if (val == 'Dark') {
local.theme = 'dark';
document.documentElement.style.setProperty("--bg", "black");
document.documentElement.style.setProperty("--color", "white");
} else if (val == 'Light') {
local.theme = 'light';
document.documentElement.style.setProperty("--bg", "rgb(206, 206, 206)");
document.documentElement.style.setProperty("--color", "black");
}
if (cookies) {
localStorage.setItem("siteData", JSON.stringify(local));
}
},
}
});
<div id="theme">
<span>Chose the color theme you want (works now)</span>
<br>
<div>Dark/Light toggle</div>
<input type="radio" id="dark" value="Dark" v-model="picked">
<label for="dark">Dark</label>
<br>
<input type="radio" id="light" value="Light" v-model="picked">
<label for="light">Light</label>
<br><br>
<span>Current Mode: {{ picked }}</span>
</div>
You shouldn't work with DOM directly, this is no vue way.你不应该直接使用 DOM,这不是 vue 的方式。
Try to wrap your elements with a class bound to your picked property:尝试使用绑定到您选择的属性的 class 来包装您的元素:
new Vue({ el: '#theme', data: { picked: 'default' } });
.dark{ background-color: rgb(206, 206, 206); color: #fff; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.10/vue.js"></script> <div id="theme" v-bind:class="picked"> <span>Chose the color theme you want (works now)</span> <br> <div>Dark/Light toggle</div> <input type="radio" id="dark" value="dark" v-model="picked"> <label for="dark">Dark</label> <br> <input type="radio" id="light" value="light" v-model="picked"> <label for="light">Light</label> <br><br> <span>Current Mode: {{ picked }}</span> </div>
If you need to change the view (condition) of the parent component, you can connect npm install vuex --save
and reactively change the view via shared storage just like now using data.picked.如果您需要更改父组件的视图(条件),您可以连接npm install vuex --save
并通过共享存储响应更改视图,就像现在使用 data.picked 一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.