一、样式文件的引用
1.1 使用<style>
标签
在Vue单文件组件(.vue文件)中,最直接的方式是在<style>
标签中编写CSS代码。
<template>
<div class="my-component">Hello, Vue!</div>
</template>
<style>
.my-component {
color: blue;
font-size: 16px;
}
</style>
1.2 引入外部CSS文件
如果你有单独的CSS文件,可以使用@import
语法将其引入。
<template>
<div class="my-component">Hello, Vue!</div>
</template>
<style>
@import './styles/my-style.css';
</style>
1.3 使用Sass/SCSS
Vue也支持Sass/SCSS,需要在项目中安装相应的loader。
<template>
<div class="my-component">Hello, Vue!</div>
</template>
<style lang="scss">
.my-component {
color: blue;
font-size: 16px;
&:hover {
color: red;
}
}
</style>
二、图片路径的引用
2.1 静态资源目录(Public)
<template>
<img src="/images/image.jpg" alt="description">
</template>
2.2 作为模块导入
<template>
<img :src="imageUrl" alt="description">
</template>
<script>
import imageUrl from '@/assets/image.jpg';
export default {
data() {
return {
imageUrl
};
}
}
</script>
2.3 动态路径
<template>
<img :src="dynamicImageUrl" alt="description">
</template>
<script>
export default {
data() {
return {
dynamicImageUrl: '@/assets/image.jpg'
};
},
methods: {
changeImage() {
this.dynamicImageUrl = '@/assets/another-image.jpg';
}
}
}
</script>
三、实战案例
3.1 案例:组件中使用背景图
<template>
<div class="background-image"></div>
</template>
<style scoped>
.background-image {
background-image: url('~@/assets/background.jpg');
width: 100%;
height: 300px;
}
</style>
3.2 案例:动态加载图片
<template>
<img :src="getImageUrl(imageName)" alt="dynamic image">
</template>
<script>
export default {
data() {
return {
imageName: 'image1.jpg'
};
},
methods: {
getImageUrl(name) {
return require(`@/assets/${name}`);
}
}
}
</script>
四、常见问题及解决方案
4.1 相对路径问题
4.2 图片不显示
4.3 打包后路径问题
现代前端工具如Vue CLI、Vite会在构建过程中处理静态资源,可能会修改文件名以支持缓存。确保在引用时使用正确的路径。
五、总结
希望这篇指南对你有所帮助,祝你在Vue开发的道路上越走越远!