Home > Web Front-end > Vue.js > An article to talk about the commonly used built-in instructions in Vue [Encyclopedia]

An article to talk about the commonly used built-in instructions in Vue [Encyclopedia]

青灯夜游
Release: 2022-09-06 19:53:08
forward
2393 people have browsed it

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.

An article to talk about the commonly used built-in instructions in Vue [Encyclopedia]

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>
Copy after login

1. v-on

Instructions: Bind elements Event listener.

Abbreviation: @

Parameters: event (optional when using object syntax)

Modifier:

  • .stop - Call event.stopPropagation().
  • .prevent ——Call event.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(&#39;hello&#39;, $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>
Copy after login

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 or style 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="&#39;/path/to/images/&#39; + 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 + &#39;px&#39; }"></div>
<div :style="[styleObjectA, styleObjectB]"></div>

<!-- 绑定对象形式的 attribute -->
<div v-bind="{ id: someProp, &#39;other-attr&#39;: otherProp }"></div>

<!-- prop 绑定。“prop” 必须在子组件中已声明。 -->
<MyComponent :prop="someThing" />

<!-- 传递子父组件共有的 prop -->
<MyComponent v-bind="$props" />

<!-- XLink -->
<svg><a :xlink:special="foo"></a></svg>
Copy after login

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>
Copy after login

4. v-else

说明: 表示 v-ifv-if / v-else-if 链式调用的“else 块”。

<h2 v-if="isShow">Coder</h2>
<h2 v-else>Bin</h2>
Copy after login

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>
Copy after login

v-model 后面会说明

6. v-show

说明基于表达式值的真假性,来改变元素的可见性。

详细描述v-show 通过设置内联样式的 display CSS 属性来工作,当元素可见时将使用初始 display 值。当条件改变时,也会触发过渡效果。

  <template id="my-app">
    <h2 v-show="isShow">哈哈哈哈</h2>
  </template>

  <script>
    const App = {
      template: &#39;#my-app&#39;,
      data() {
        return {
          isShow: true
        }
      }
    }
    Vue.createApp(App).mount(&#39;#app&#39;);
  </script>
Copy after login

v-show 不支持在 <template> 元素上使用,也不能和 v-else 搭配使用。

7. v-model

说明: 在表单输入元素或组件上创建双向绑定。

仅限: <input><select><textarea>、components

修饰符:

  • .lazy ——监听 change 事件而不是 input
  • .number ——将输入的合法符串转为数字
  • .trim ——移除输入内容两端空格

基本使用:

  <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: &#39;#my-app&#39;,
      data() {
        return {
          message: "Hello World"
        }
      },
      methods: {
        inputChange(event) {
          this.message = event.target.value;
        }
      }
    }
    Vue.createApp(App).mount(&#39;#app&#39;);
Copy after login

绑定其他表单:

  <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: &#39;#my-app&#39;,
      data() {
        return {
          intro: "Hello World",
          isAgree: false,
          hobbies: ["basketball"],
          gender: "",
          fruit: "orange"
        }
      },
      methods: {
        commitForm() {
          axios
        }
      }
    }

    Vue.createApp(App).mount(&#39;#app&#39;);
  </script>
Copy after login

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: &#39;#my-app&#39;,
      data() {
        return {
          message: "Hello World"
        }
      },
      methods: {
        showType() {
          console.log(this.message, typeof this.message);
        },
        showResult() {
          console.log(this.message);
        }
      }
    }

    Vue.createApp(App).mount(&#39;#app&#39;);
  </script>
Copy after login

8. v-for

说明: 基于原始数据多次渲染元素或模板块。

详细描述:

指令值必须使用特殊语法 alias in expression 为正在迭代的元素提供一个别名:

<div v-for="item in items">
  {{ item.text }}
</div>
Copy after login

或者,你也可以为索引指定别名 (如果用在对象,则是键值):

<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>
Copy after login

v-for 的默认方式是尝试就地更新元素而不移动它们。要强制其重新排序元素,你需要用特殊 attribute key 来提供一个排序提示:

<div v-for="item in items" :key="item.id">
  {{ item.text }}
</div>
Copy after login

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>
Copy after login

10. v-text

说明: 更新元素的文本内容。

详细描述: v-text 通过设置元素的 textContent 属性来工作,因此它将覆盖元素中所有现有的内容。如果你需要更新 textContent 的部分,应该使用 mustache interpolations 代替。

<span v-text="msg"></span>
<!-- 等同于 -->
<span>{{msg}}</span>
Copy after login

11. v-html

说明: 更新元素的 innerHTML

详细描述: v-html 的内容直接作为普通 HTML 插入—— Vue 模板语法是不会被解析的。如果你发现自己正打算用 v-html 来编写模板,不如重新想想怎么使用组件来代替。

安全说明: 在你的站点上动态渲染任意的 HTML 是非常危险的,因为它很容易导致 XSS 攻击。请只对可信内容使用 HTML 插值,绝不要将用户提供的内容作为插值

<div v-html="html"></div>
Copy after login

12. v-pre

说明: 跳过该元素及其所有子元素的编译。

详细描述:元素内具有 v-pre,所有 Vue 模板语法都会被保留并按原样渲染。最常见的用例就是显示原始双大括号标签及内容。

<span v-pre>{{ this will not be compiled }}</span>
Copy after login

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>
Copy after login

14. v-cloak

说明: 用于隐藏尚未完成编译的 DOM 模板。

详细描述:该指令只在没有构建步骤的环境下需要使用。

  • 当使用直接在 DOM 中书写的模板时,可能会出现一种叫做“未编译模板闪现”的情况:用户可能先看到的是还没编译完成的双大括号标签,直到挂载的组件将它们替换为实际渲染的内容。
  • v-cloak 会保留在所绑定的元素上,直到相关组件实例被挂载后才移除。配合像 [v-cloak] { display: none } 这样的 CSS 规则,它可以在组件编译完毕前隐藏原始模板。
[v-cloak] {
  display: none;
}
Copy after login
<div v-cloak>
  {{ message }}
</div>
Copy after login

更多编程相关知识,请访问:编程入门!!

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!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template