一:先寫好兩個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>
完成效果