概述
v-bind指令可以说是Vue3中最常用的指令之一,使用v-bind,我们几乎能够给任何实现动态的绑定比值。
这里,我们主要演示以下,通过v-bind动态绑定CSS样式。
基本用法
我们创建src/components/Demo11.vue,在这个组件中,我们要:
- 场景1:动态绑定一个CSS样式
- 场景2:动态绑定一个CSS样式类
代码如下:
<script setup>
const styleObj = {
color: "red",
fontSize: "33px",
}
</script>
<template>
<div :style="styleObj">styleObj 动态样式</div>
<div :class="{active:true}">动态样式类:true</div>
<div :class="{active:false}">动态样式类:false</div>
</template>
<style>
.active {
color: yellow;
}
</style>
接着,我们修改src/App.vue,引入Demo11.vue并进行渲染:
<script setup>
import Demo from "./components/Demo11.vue"
</script>
<template>
<h1>欢迎跟着Python私教一起学习Vue3入门课程</h1>
<hr>
<Demo/>
</template>
然后,我们浏览器访问:http://localhost:5173/
完整代码
package.json
{
"name": "hello",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build"
},
"dependencies": {
"vue": "^3.3.8"
},
"devDependencies": {
"@vitejs/plugin-vue": "^4.5.0",
"vite": "^5.0.0"
}
}
vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
})
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + Vue</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>
src/main.js
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
src/App.vue
<script setup>
import Demo from "./components/Demo11.vue"
</script>
<template>
<h1>欢迎跟着Python私教一起学习Vue3入门课程</h1>
<hr>
<Demo/>
</template>
src/components/Demo11.vue
<script setup>
const styleObj = {
color: "red",
fontSize: "33px",
}
</script>
<template>
<div :style="styleObj">styleObj 动态样式</div>
<div :class="{active:true}">动态样式类:true</div>
<div :class="{active:false}">动态样式类:false</div>
</template>
<style>
.active {
color: yellow;
}
</style>
启动方式
yarn
yarn dev
浏览器访问:http://localhost:5173/