新吴网站建设,wordpress热门主题,网络系统运维,建设协会网站的公司概述
v-if指令主要用来实现条件渲染#xff0c;在实际项目中使用得也非常多。
v-if通常会配合v-else-if、v-else指令一起使用#xff0c;可以达到多个条件执行一个#xff0c;两个条件执行一个#xff0c;满足一个条件执行等多种场景。
下面#xff0c;我们分别演示这三…概述
v-if指令主要用来实现条件渲染在实际项目中使用得也非常多。
v-if通常会配合v-else-if、v-else指令一起使用可以达到多个条件执行一个两个条件执行一个满足一个条件执行等多种场景。
下面我们分别演示这三种使用场景。
基本用法
我们创建src/components/Demo12.vue在这个组件中我们要
场景1v-if单独使用如果count大于0则显示“数字大于0了”。场景2v-if和v-else配合使用如果count大于20则显示“数字大于20了”否则显示“数字小于或者等于20”场景3v-if、v-else-if、v-else配合使用如果count大于100则显示“数字大于100了”如果count等于100则显示“数字等于100了”否则显示“数字小于100了”
为了便于查看效果我们还要通过两个按钮一个按钮控制count的增加另一个按钮控制count的减少。
代码如下
script setup
import {ref} from vue;const count ref(33)
/script
templatediv v-ifcount0数字大于0了/divhrdiv v-ifcount20数字大于20了/divdiv v-else数字小于或者等于20/divhrdiv v-ifcount100数字大于100了/divdiv v-else-ifcount100数字等于100了/divdiv v-else数字小于100了/divhrdivh3{{ count }}/h3button clickcount10增加/buttonbutton clickcount-10减少/button/div
/template接着我们修改src/App.vue引入Demo12.vue并进行渲染
script setup
import Demo from ./components/Demo12.vue
/script
templateh1欢迎跟着Python私教一起学习Vue3入门课程/h1hrDemo/
/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-vueexport default defineConfig({plugins: [vue()],
})index.html
!doctype html
html langenheadmeta charsetUTF-8 /link relicon typeimage/svgxml href/vite.svg /meta nameviewport contentwidthdevice-width, initial-scale1.0 /titleVite Vue/title/headbodydiv idapp/divscript typemodule src/src/main.js/script/body
/htmlsrc/main.js
import { createApp } from vue
import App from ./App.vuecreateApp(App).mount(#app)src/App.vue
script setup
import Demo from ./components/Demo12.vue
/script
templateh1欢迎跟着Python私教一起学习Vue3入门课程/h1hrDemo/
/templatesrc/components/Demo12.vue
script setup
import {ref} from vue;const count ref(33)
/script
templatediv v-ifcount0数字大于0了/divhrdiv v-ifcount20数字大于20了/divdiv v-else数字小于或者等于20/divhrdiv v-ifcount100数字大于100了/divdiv v-else-ifcount100数字等于100了/divdiv v-else数字小于100了/divhrdivh3{{ count }}/h3button clickcount10增加/buttonbutton clickcount-10减少/button/div
/template启动方式
yarn
yarn dev浏览器访问http://localhost:5173/