


An article to talk about the commonly used built-in instructions in Vue [Encyclopedia]
This article reviews and summarizes all the built-in instructions of Vue. Some common instructions will be explained first, and the less commonly used instructions will be placed at the back.
0. Interpolation expression
Explanation: Interpolation expression is also called Mustache syntax (i.e. double braces), the double brace tag will be replaced by the value of the msg
attribute in the corresponding component instance. At the same time, it will also be updated synchronously every time the msg
attribute changes. [Related recommendations: vuejs video tutorial]
<template id="my-app"> <!-- 1.mustache的基本使用 --> <h2>{{message}} - {{message}}</h2> <!-- 2.是一个表达式 --> <h2>{{counter * 10}}</h2> <h2>{{ message.split(" ").reverse().join(" ") }}</h2> <!-- 3.也可以调用函数 --> <!-- 可以使用computed(计算属性) --> <h2>{{getReverseMessage()}}</h2> <!-- 4.三元运算符 --> <h2>{{ isShow ? "哈哈哈": "" }}</h2> <button @click="toggle">切换</button> <!-- 错误用法 --> <!-- var name = "abc" -> 赋值语句 --> <!-- <h2>{{var name = "abc"}}</h2> <h2>{{ if(isShow) { return "哈哈哈" } }}</h2> --> </template>
1. v-on
Instructions: Bind elements Event listener.
Abbreviation: @
Parameters: event
(optional when using object syntax)
Modifier:
-
.stop
- Callevent.stopPropagation()
. -
.prevent
——Callevent.preventDefault()
. -
.capture
- Add event listener in capture mode. -
.self
- The handler function is only triggered when the event is emitted from the element itself. -
.{keyAlias}
- The processing function is only triggered under certain keys. -
.once
——The processing function is triggered at most once. -
.left
- Only triggers the handler function on the left mouse button event. -
.right
- Only triggers the handler function on the right mouse button event. -
.middle
——The handler function is only triggered on the middle mouse button event. -
.passive
- Attach a DOM event via{ passive: true }
.
Detailed description: The event type is specified by parameters. The expression can be a method name, an inline declaration, or can be omitted if modifiers are present.
- When used for ordinary elements, only listen to native DOM events. When used in custom element components, listen to custom events triggered by child components.
- When listening to native DOM events, the method receives the native event as the only parameter. If an inline declaration is used, the declaration has access to a special
$event
variable:v-on:click="handle('ok', $event)"
. -
v-on
also supports binding objects of event/listener pairs without parameters. Note that when using object syntax, no modifiers are supported.
<!-- 方法处理函数 --> <button v-on:click="doThis"></button> <!-- 动态事件 --> <button v-on:[event]="doThis"></button> <!-- 内联声明 --> <button v-on:click="doThat('hello', $event)"></button> <!-- 缩写 --> <button @click="doThis"></button> <!-- 使用缩写的动态事件 --> <button @[event]="doThis"></button> <!-- 停止传播 --> <button @click.stop="doThis"></button> <!-- 阻止默认事件 --> <button @click.prevent="doThis"></button> <!-- 不带表达式地阻止默认事件 --> <form @submit.prevent></form> <!-- 链式调用修饰符 --> <button @click.stop.prevent="doThis"></button> <!-- 按键用于 keyAlias 修饰符--> <input @keyup.enter="onEnter" /> <!-- 点击事件将最多触发一次 --> <button v-on:click.once="doThis"></button> <!-- 对象语法 --> <button v-on="{ mousedown: doThis, mouseup: doThat }"></button>
Description: Dynamically bind one or more attributes, which can also be props of components.
Abbreviation: :
or .
(when using the .prop
modifier)
Modifier:
.camel
- Convert attributes named with dashes into camel case naming..prop
- Force binding to DOM property. 3.2.attr
- forced binding to DOM attribute. 3.2
Usage:
- When used to bind
class
orstyle
attribute,v-bind
Supports additional value types such as arrays or objects. See the guide link below for details. - When processing binding, Vue will use the
in
operator by default to check whether a DOM property with the same name as the bound key is defined on the element. If a property with the same name exists, Vue will assign it as a DOM property instead of setting it as an attribute. This behavior is consistent with the expected binding value type in most cases, but you can also explicitly force the binding mode using the.prop
and.attr
modifiers. Sometimes this is necessary, especially when dealing with Custom Elements. - When used for component props binding, the bound props must be correctly declared in the child component.
- When used without parameters, it can be used to bind an object containing multiple attribute name-binding value pairs.
<!-- 绑定 attribute --> <img v-bind:src="imageSrc" /> <!-- 动态 attribute 名 --> <button v-bind:[key]="value"></button> <!-- 缩写 --> <img :src="imageSrc" /> <!-- 缩写形式的动态 attribute 名 --> <button :[key]="value"></button> <!-- 内联字符串拼接 --> <img :src="'/path/to/images/' + fileName" /> <!-- class 绑定 --> <div :class="{ red: isRed }"></div> <div :class="[classA, classB]"></div> <div :class="[classA, { classB: isB, classC: isC }]"></div> <!-- style 绑定 --> <div :style="{ fontSize: size + 'px' }"></div> <div :style="[styleObjectA, styleObjectB]"></div> <!-- 绑定对象形式的 attribute --> <div v-bind="{ id: someProp, 'other-attr': otherProp }"></div> <!-- prop 绑定。“prop” 必须在子组件中已声明。 --> <MyComponent :prop="someThing" /> <!-- 传递子父组件共有的 prop --> <MyComponent v-bind="$props" /> <!-- XLink --> <svg><a :xlink:special="foo"></a></svg>
3. v-if
Description: Conditionally render elements based on the truth or falsehood of the expression value Or a template fragment.
<h2 v-if="isShow">哈哈哈哈</h2>
4. v-else
说明: 表示 v-if
或 v-if
/ v-else-if
链式调用的“else 块”。
<h2 v-if="isShow">Coder</h2> <h2 v-else>Bin</h2>
ishow 为 true 显示 Coder,反之显示 Bin
5. v-else-if
说明: 表示 v-if
的“else if 块”。可以进行链式调用。
<template id="my-app"> <input type="text" v-model="score"> <h2 v-if="score > 90">优秀</h2> <h2 v-else-if="score > 60">良好</h2> <h2 v-else>不及格</h2> </template>
v-model 后面会说明
6. v-show
说明:基于表达式值的真假性,来改变元素的可见性。
详细描述:v-show
通过设置内联样式的 display
CSS 属性来工作,当元素可见时将使用初始 display
值。当条件改变时,也会触发过渡效果。
<template id="my-app"> <h2 v-show="isShow">哈哈哈哈</h2> </template> <script> const App = { template: '#my-app', data() { return { isShow: true } } } Vue.createApp(App).mount('#app'); </script>
v-show
不支持在 <template>
元素上使用,也不能和 v-else
搭配使用。
7. v-model
说明: 在表单输入元素或组件上创建双向绑定。
仅限: <input>
、<select>
、 <textarea>
、components
修饰符:
基本使用:
<template id="my-app"> <!-- 1.v-bind value的绑定 2.监听input事件, 更新message的值 --> <!-- <input type="text" :value="message" @input="inputChange"> --> <input type="text" v-model="message"> <h2>{{message}}</h2> </template> <script> const App = { template: '#my-app', data() { return { message: "Hello World" } }, methods: { inputChange(event) { this.message = event.target.value; } } } Vue.createApp(App).mount('#app');
绑定其他表单:
<template id="my-app"> <!-- 1.绑定textarea --> <label for="intro"> 自我介绍 <textarea name="intro" id="intro" cols="30" rows="10" v-model="intro"></textarea> </label> <h2>intro: {{intro}}</h2> <!-- 2.checkbox --> <!-- 2.1.单选框 --> <label for="agree"> <input id="agree" type="checkbox" v-model="isAgree"> 同意协议 </label> <h2>isAgree: {{isAgree}}</h2> <!-- 2.2.多选框 --> <span>你的爱好: </span> <label for="basketball"> <input id="basketball" type="checkbox" v-model="hobbies" value="basketball"> 篮球 </label> <label for="football"> <input id="football" type="checkbox" v-model="hobbies" value="football"> 足球 </label> <label for="tennis"> <input id="tennis" type="checkbox" v-model="hobbies" value="tennis"> 网球 </label> <h2>hobbies: {{hobbies}}</h2> <!-- 3.radio --> <span>你的爱好: </span> <label for="male"> <input id="male" type="radio" v-model="gender" value="male">男 </label> <label for="female"> <input id="female" type="radio" v-model="gender" value="female">女 </label> <h2>gender: {{gender}}</h2> <!-- 4.select --> <span>喜欢的水果: </span> <select v-model="fruit" multiple size="2"> <option value="apple">苹果</option> <option value="orange">橘子</option> <option value="banana">香蕉</option> </select> <h2>fruit: {{fruit}}</h2> </template> <script> const App = { template: '#my-app', data() { return { intro: "Hello World", isAgree: false, hobbies: ["basketball"], gender: "", fruit: "orange" } }, methods: { commitForm() { axios } } } Vue.createApp(App).mount('#app'); </script>
v-model修饰符的使用
<template id="my-app"> <!-- 1.lazy修饰符 --> <!-- <input type="text" v-model.lazy="message"> --> <!-- 2.number修饰符 --> <!-- <input type="text" v-model.number="message"> <h2>{{message}}</h2> <button @click="showType">查看类型</button> --> <!-- 3.trim修饰符 --> <input type="text" v-model.trim="message"> <button @click="showResult">查看结果</button> </template> <script> const App = { template: '#my-app', data() { return { message: "Hello World" } }, methods: { showType() { console.log(this.message, typeof this.message); }, showResult() { console.log(this.message); } } } Vue.createApp(App).mount('#app'); </script>
8. v-for
说明: 基于原始数据多次渲染元素或模板块。
详细描述:
指令值必须使用特殊语法 alias in expression
为正在迭代的元素提供一个别名:
<div v-for="item in items"> {{ item.text }} </div>
或者,你也可以为索引指定别名 (如果用在对象,则是键值):
<div v-for="(item, index) in items"></div> <div v-for="(value, key) in object"></div> <div v-for="(value, name, index) in object"></div>
v-for
的默认方式是尝试就地更新元素而不移动它们。要强制其重新排序元素,你需要用特殊 attribute key
来提供一个排序提示:
<div v-for="item in items" :key="item.id"> {{ item.text }} </div>
9. v-slot
说明: 用于声明具名插槽或是期望接收 props 的作用域插槽。
缩写: #
参数:插槽名 (可选,默认是 default
)
仅限:
<template>
- components (用于带有 prop 的单个默认插槽)
示例
<!-- 具名插槽 --> <BaseLayout> <template v-slot:header> Header content </template> <template v-slot:default> Default slot content </template> <template v-slot:footer> Footer content </template> </BaseLayout> <!-- 接收 prop 的具名插槽 --> <InfiniteScroll> <template v-slot:item="slotProps"> <div class="item"> {{ slotProps.item.text }} </div> </template> </InfiniteScroll> <!-- 接收 prop 的默认插槽,并解构 --> <Mouse v-slot="{ x, y }"> Mouse position: {{ x }}, {{ y }} </Mouse>
10. v-text
说明: 更新元素的文本内容。
详细描述: v-text
通过设置元素的 textContent 属性来工作,因此它将覆盖元素中所有现有的内容。如果你需要更新 textContent
的部分,应该使用 mustache interpolations 代替。
<span v-text="msg"></span> <!-- 等同于 --> <span>{{msg}}</span>
11. v-html
说明: 更新元素的 innerHTML。
详细描述: v-html
的内容直接作为普通 HTML 插入—— Vue 模板语法是不会被解析的。如果你发现自己正打算用 v-html
来编写模板,不如重新想想怎么使用组件来代替。
安全说明: 在你的站点上动态渲染任意的 HTML 是非常危险的,因为它很容易导致 XSS 攻击。请只对可信内容使用 HTML 插值,绝不要将用户提供的内容作为插值
<div v-html="html"></div>
12. v-pre
说明: 跳过该元素及其所有子元素的编译。
详细描述:元素内具有 v-pre
,所有 Vue 模板语法都会被保留并按原样渲染。最常见的用例就是显示原始双大括号标签及内容。
<span v-pre>{{ this will not be compiled }}</span>
13. v-once
说明: 跳过该元素及其所有子元素的编译。
详细描述: 在随后的重新渲染,元素/组件及其所有子项将被当作静态内容并跳过渲染。这可以用来优化更新时的性能。
<!-- 单个元素 --> <span v-once>This will never change: {{msg}}</span> <!-- 带有子元素的元素 --> <div v-once> <h1>comment</h1> <p>{{msg}}</p> </div> <!-- 组件 --> <MyComponent v-once :comment="msg" /> <!-- `v-for` 指令 --> <ul> <li v-for="i in list" v-once>{{i}}</li> </ul>
14. v-cloak
说明: 用于隐藏尚未完成编译的 DOM 模板。
详细描述:该指令只在没有构建步骤的环境下需要使用。
- 当使用直接在 DOM 中书写的模板时,可能会出现一种叫做“未编译模板闪现”的情况:用户可能先看到的是还没编译完成的双大括号标签,直到挂载的组件将它们替换为实际渲染的内容。
v-cloak
会保留在所绑定的元素上,直到相关组件实例被挂载后才移除。配合像[v-cloak] { display: none }
这样的 CSS 规则,它可以在组件编译完毕前隐藏原始模板。
[v-cloak] { display: none; }
<div v-cloak> {{ message }} </div>
更多编程相关知识,请访问:编程入门!!
The above is the detailed content of An article to talk about the commonly used built-in instructions in Vue [Encyclopedia]. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

There are three ways to refer to JS files in Vue.js: directly specify the path using the <script> tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses <router-link to="/" component window.history.back(), and the method selection depends on the scene.

You can query the Vue version by using Vue Devtools to view the Vue tab in the browser's console. Use npm to run the "npm list -g vue" command. Find the Vue item in the "dependencies" object of the package.json file. For Vue CLI projects, run the "vue --version" command. Check the version information in the <script> tag in the HTML file that refers to the Vue file.
