项目需求,可以动态更换皮肤的css样式。并且用cookie保存7天
最早的做法是
require(“skin.css”)的方式来做到引用。
但vue打包以后所有的css文件到压缩在了一起所以只显示最后一个样式。
最后用的是在public 中的index.html中用原始的方式引用css,效果很好。下面就看一下吧
代码:
在index.html中引用默认的css
<link class="skinLink" rel="stylesheet" href="/styles/chunfen.css">
引用方式
skin.setAttribute('href', './styles/chunfen.css')
涉及知识有:
1.子组建向父组建传参
changeDefault: function (item) {
this.styleSkin = item
this.$emit('childByCss', styleSkin) //这里是重点,定义父组件接收的方法:childByCss,传入参数:styleSkin
},
2.父组建import引用并定义组建
<skin v-on:childByCss="childByCss" style="margin-right: 10px;"/> // childByCss:父组件引用子组件的方法, childByCss 参数
3.实现
/* 设置动态皮肤--接收skin 子组件的值 */
childByCss (childByCss) {
/* cookies设置 */
let skin = document.querySelector('.skinLink') //获取index.html中的连<link/>
let cookies = Cookies.get(this.$store.state.user.userAccount)
if (cookies !== '' || cookies !== null || cookies !== undefined) {
Cookies.remove(this.$store.state.user.userAccount)
Cookies.set(this.$store.state.user.userAccount, '' + childByCss, { expires: 7 })// cookies设置有效天数7天,这里的cookies用的是 js-cookies
} else {
Cookies.set(this.$store.state.user.userAccount, '' + childByCss, { expires: 7 })
}
skin.setAttribute('href', childByCss) //重点----- 更换css
}
4.js-cookies下载插件
安装:
npm install js-cookie --save
引用:
import Cookies from 'js-cookie'
保存:
// Create a cookie, valid across the entire site:
Cookies.set('name', 'value');
// Create a cookie that expires 7 days from now, valid across the entire site:
Cookies.set('name', 'value', { expires: 7 });
// Create an expiring cookie, valid to the path of the current page:
Cookies.set('name', 'value', { expires: 7, path: '' });
读取:
// Read cookie:
Cookies.get('name'); // => 'value'
Cookies.get('nothing'); // => undefined
// Read all visible cookies:
Cookies.get(); // => { name: 'value' }
删除:
// Delete cookie:
Cookies.remove('name');
// Delete a cookie valid to the path of the current page:
Cookies.set('name', 'value', { path: '' });
Cookies.remove('name'); // fail!
Cookies.remove('name', { path: '' }); // removed!