1. 程式人生 > 實用技巧 >vue 切換主題(換膚)功能

vue 切換主題(換膚)功能

一:先寫好兩個css樣式放在static資料夾中

二:在index.html中新增css link連結

<link rel="stylesheet" id="style" href="static/css/one.css">

三:在App.vue中的created中新增預設執行方法

created() {
var style = localStorage.getItem("style");
if(style){
document.getElementById('style').setAttribute("href",style); //實現將主題儲存在記憶體中重新整理瀏覽器不改變
}
}

四:最後在需要的頁面寫上切換主題功能

<template>
<div>
<div class="box-body">主題切換</div>
<button @click="change(1)">切換到紫色主題</button>
<button @click="change(2)">切換到藍色主題</button>
</div>
</template>
<script>
export default {
name: "ThemeBody",
data(){
return{
body_now:null
}
},
methods:{
change:function (type) {
if(type == 1){
document.getElementById('style').setAttribute("href","../static/css/one.css");
localStorage.setItem("style","../static/css/one.css");
}else if(type == 2){
document.getElementById('style').setAttribute("href","../static/css/two.css");
localStorage.setItem("style","../static/css/two.css");
}
}
}
}
</script>

<style scoped>

</style>

完成效果