Home Web Front-end Vue.js Understand common instructions in vue.js (summary)

Understand common instructions in vue.js (summary)

Nov 06, 2020 pm 05:58 PM
vue.js instruction

Understand common instructions in vue.js (summary)

v-text

v-text is mainly used to update textContent, which can be equivalent to the text attribute of JS.

<span v-text="text"></span>
// 等同于下方语句: 
<span>{{text}}</span>
Copy after login

v-html

The double brace method will interpret the data as plain text, not HTML. In order to output real HTML, you can use the v-html command. It is equivalent to JS's innerHtml property.

Note: Content is inserted as normal HTML - will not be compiled as a Vue template.

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

v-show

Equivalent to css's dispaly attribute switching between "none" and "block" settings.

<div v-show="isShow">hello world</div>
Copy after login
Copy after login

v-if

v-if can implement conditional rendering. Vue will render elements based on the true and false conditions of the expression value. .

<div v-show="isShow">hello world</div>
Copy after login
Copy after login

The above code, if isShow is false, the div is rendered, otherwise it is not rendered.

Note:

v-if needs to be distinguished from v-show. The elements of v-show will always be rendered and saved in the dom. It just simply switches the dispaly attribute of css.

v-if has higher switching overhead.

v-show has higher initial rendering overhead.

So, if you want to switch very frequently, it is better to use v-show; if the conditions are unlikely to change during runtime, it is better to use v-if.

v-else

v-else is used with v-if, it must follow v-if or v-else -if after, otherwise it has no effect.
Similar to JS’s if .. else.

<div v-if="isSow">值为true的时候显示的内容</div>
<div v-else>值为false的时候显示的内容</div>
Copy after login

v-else-if

v-else-if acts as the else-if block of v-if and can be used in a chain repeatedly. Similar to JS's if .. else if .. else

<div v-if="type===&#39;A&#39;">
  A
</div>
<div v-if="type===&#39;B&#39;">
  B
</div>
<div v-if="type===&#39;C&#39;">
  C
</div>
<div v-else>
  Not A,B,C
</div>
Copy after login

v-for

Use the v-for instruction to render by traversing the array .

<ul>
	<li v-for="item in items">{{item.name}}</li>
</ul>

<script>
new Vue({
  el: &#39;#app&#39;,
  data: {
    items: [
      { name: &#39;Runoob&#39; },
      { name: &#39;Google&#39; },
      { name: &#39;Taobao&#39; }
    ]
  }
})
</script>

// 补充:
// 也可以自行指定参数,最多可以接受3个参数
<div v-for="(item, index) in items"></div>
<div v-for="(val, key) in object"></div>
<div v-for="(val, name, index) in object"></div>

// 迭代对象
<ul>
    <li v-for="value in object">
     {{ index }}. {{ key }} : {{ value }}
</li>

// 迭代整数
<ul>
    <li v-for="n in 10">
     {{ n }}
    </li>
</ul>
Copy after login

v-on

Bind event listener. The event type is specified by parameters. The expression can be the name of a method or an inline statement, and can be omitted if there are no modifiers.
v-on can also be abbreviated as "@", such as:

v-on="show" can be abbreviated as: @show

<!-- 方法处理器 -->
<button v-on:click="doThis"></button>

<!-- 动态事件 (2.6.0+) -->
<button v-on:[event]="doThis"></button>

<!-- 内联语句 -->
<button v-on:click="doThat(&#39;hello&#39;, $event)"></button>

<!-- 缩写 -->
<button @click="doThis"></button>

<!-- 动态事件缩写 (2.6.0+) -->
<button @[event]="doThis"></button>

<!-- 停止冒泡 -->
<button @click.stop="doThis"></button>

<!-- 阻止默认行为 -->
<button @click.prevent="doThis"></button>

<!-- 阻止默认行为,没有表达式 -->
<form @submit.prevent></form>

<!--  串联修饰符 -->
<button @click.stop.prevent="doThis"></button>

<!-- 键修饰符,键别名 -->
<input @keyup.enter="onEnter">

<!-- 键修饰符,键代码 -->
<input @keyup.13="onEnter">

<!-- 点击回调只会触发一次 -->
<button v-on:click.once="doThis"></button>

<!-- 对象语法 (2.4.0+) -->
<button v-on="{ mousedown: doThis, mouseup: doThat }"></button>
Copy after login

You can also use modifiers, as follows :

.stop - Call event.stopPropagation().

.prevent - Calls event.preventDefault().

.capture - Use capture mode when adding event listeners.

.self - The callback is only triggered when the event is triggered from the element itself to which the listener is bound.

.{keyCode | keyAlias} - The callback is only fired when the event is triggered from a specific key.

.native - Listen to native events on the root element of the component.

.once - The callback is triggered only once.

.left - only fires when the left mouse button is clicked.

.right - only triggered when the right mouse button is clicked.

.middle - only triggered when the middle mouse button is clicked.

.passive - add a listener in { passive: true } mode

v-bind

Dynamically bind one or more attributes, or a component prop to an expression. Often used to dynamically bind classes and styles. And href etc.

can be abbreviated as: " : ", such as:

v-bind:class=" isActive : 'active' :' ' ", can be abbreviated as: :class=" isActive : ' active' :' ' "

<div v-bind:class=" isActive : &#39;active&#39; :&#39; &#39; "></div>
<script>
  var app = new Vue({
    el: &#39;#app&#39;,
    data: {
      isActive : true, 
    }
  })
</script>

//渲染结果为: <div class="active"></div>
Copy after login

Bind multiple classes, the details are as follows:

<div v-bind:class="[ isActive : &#39;active&#39; :&#39; &#39; , isError: &#39;error&#39; :&#39; &#39; ]">
</div>
<script>
  var app = new Vue({
    el: &#39;#app&#39;,
    data: {
      isActive : true, 
      isError:  true,
    }
  })
</script>

//渲染结果为: <div class="active error"></div>
Copy after login

Other examples, see the code below for details:

<!-- 绑定一个属性 -->
<img v-bind:src="imageSrc">

<!-- 动态特性名 (2.6.0+) -->
<button v-bind:[key]="value"></button>

<!-- 缩写 -->
<img :src="imageSrc">

<!-- 动态特性名缩写 (2.6.0+) -->
<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 }]">

<!-- style 绑定 -->
<div :style="{ fontSize: size + &#39;px&#39; }"></div>
<div :style="[styleObjectA, styleObjectB]"></div>

<!-- 绑定一个有属性的对象 -->
<div v-bind="{ id: someProp, &#39;other-attr&#39;: otherProp }"></div>

<!-- 通过 prop 修饰符绑定 DOM 属性 -->
<div v-bind:text-content.prop="text"></div>

<!-- prop 绑定。“prop”必须在 my-component 中声明。-->
<my-component :prop="someThing"></my-component>

<!-- 通过 $props 将父组件的 props 一起传给子组件 -->
<child-component v-bind="$props"></child-component>

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

v-model

#Create two-way binding on a form control or component.
v-model will ignore the initial values ​​of the value, checked, and selected attributes of all form elements. Because it selects Vue instance data as the specific value.

<div id="app">
  <input v-model="somebody">
  <p>hello {{somebody}}</p>
</div>
<script>
  var app = new Vue({
    el: &#39;#app&#39;,
    data: {
      somebody:&#39;小明&#39;
    }
  })
</script>
Copy after login

In this example, enter another name directly into the browser input, and the content of the p below will change directly accordingly. This is two-way data binding.

Available modifiers:

.lazy - By default, v-model synchronizes the value and data of the input box. You can use this modifier to switch to resynchronization in the change event.

.number - Automatically convert the user's input value into a numerical type

.trim - Automatically filter the leading and trailing spaces entered by the user

How to use modifiers: For example:

<input v-model.trim="somebody">
Copy after login

v-pre

v-pre is mainly used to skip the compilation process of this element and its sub-elements. Can be used to display the original Mustache tag. Skip a large number of nodes without instructions to speed up compilation.

<div id="app">
  <span v-pre>{{message}}</span> //这条语句不进行编译
  <span>{{message}}</span>
</div>
Copy after login

This directive is used to remain on the element until the end of the associated instance for compilation.

<div id="app" v-cloak>
  <div>
    {{message}}
  </div>
</div>
<script type="text/javascript">
  new Vue({
   el:&#39;#app&#39;,
   data:{
    message:&#39;hello world&#39;
   }
  })
</script>
Copy after login

Explanation:
will flash when the page is loaded. It will first display:

<div>
  {{message}}
</div>
Copy after login

and then compile to:

<div>
  hello world!
</div>
Copy after login

The v-cloak command can To solve the problem of interpolation flickering above, as follows: In fact, what is used is to hide the content through the style attribute when the interpolation is not loaded.

  <style>
    [v-cloak] {
       display: none; 
    }
  </style>
  
  <div id="app">
    <!-- 使用 v-cloak 能够解决 插值表达式闪烁的问题 -->
    <p v-cloak>++++++++ {{ msg }} ----------</p>
  </div>
  
  <script>
    var vm = new Vue({
      el: &#39;#app&#39;,
      data: {
        msg: &#39;hello&#39;,
      }
    })
  </script>
Copy after login

v-once

v-once关联的实例,只会渲染一次。之后的重新渲染,实例极其所有的子节点将被视为静态内容跳过,这可以用于优化更新性能。

<span v-once>This will never change:{{msg}}</span> //单个元素
<div v-once>//有子元素
  <h1>comment</h1>
  <p>{{msg}}</p>
</div>
<my-component v-once:comment="msg"></my-component> //组件
<ul>
  <li v-for="i in list">{{i}}</li>
</ul>
Copy after login

上面的例子中,msg,list即使产生改变,也不会重新渲染。

v-slot

提供具名插槽或需要接收 prop 的插槽。

可简写为:#

slot 和 scope-slot 是在 vue@2.6.x 之前的语法,而从 vue@2.6.0 开始,官方推荐我们使用 v-slot 来替代前两者。

使用具名插槽来自定义模板内容(vue@2.6.x已经废弃)

<div class="container">
  <header>
    <slot name="header"></slot>
  </header>
  <main>
    <slot></slot>
  </main>
  <footer>
    <slot name="footer"></slot>
  </footer>
</div>
Copy after login

在向具名插槽提供内容的时候,我们可以在一个父组件的 元素上使用 slot 特性:

<base-layout>
  <template slot="header">
    <h1>Here might be a page title</h1>
  </template>

  <p>A paragraph for the main content.</p>
  <p>And another one.</p>

  <template slot="footer">
    <p>Here&#39;s some contact info</p>
  </template>
</base-layout>
Copy after login

接下来,使用 v-slot 指令改写上面的栗子:

<base-layout>
  <template v-slot:header>
    <h1>Here might be a page title</h1>
  </template>

  <p>A paragraph for the main content.</p>
  <p>And another one.</p>

  <template v-slot:footer>
    <p>Here&#39;s some contact info</p>
  </template>
</base-layout>
Copy after login

使用 # 简写代替 v-slot

<base-layout>
  <template #header>
    <h1>Here might be a page title</h1>
  </template>

  <p>A paragraph for the main content.</p>
  <p>And another one.</p>

  <template #footer>
    <p>Here&#39;s some contact info</p>
  </template>
</base-layout>
Copy after login

相关推荐:

2020年前端vue面试题大汇总(附答案)

vue教程推荐:2020最新的5个vue.js视频教程精选

更多编程相关知识,请访问:编程教学!!

The above is the detailed content of Understand common instructions in vue.js (summary). For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to get items using commands in Terraria? -How to collect items in Terraria? How to get items using commands in Terraria? -How to collect items in Terraria? Mar 19, 2024 am 08:13 AM

How to get items using commands in Terraria? 1. What is the command to give items in Terraria? In the Terraria game, giving command to items is a very practical function. Through this command, players can directly obtain the items they need without having to fight monsters or teleport to a certain location. This can greatly save time, improve the efficiency of the game, and allow players to focus more on exploring and building the world. Overall, this feature makes the gaming experience smoother and more enjoyable. 2. How to use Terraria to give item commands 1. Open the game and enter the game interface. 2. Press the &quot;Enter&quot; key on the keyboard to open the chat window. 3. Enter the command format in the chat window: &quot;/give[player name][item ID][item quantity]&quot;.

In-depth discussion of how vite parses .env files In-depth discussion of how vite parses .env files Jan 24, 2023 am 05:30 AM

When using the Vue framework to develop front-end projects, we will deploy multiple environments when deploying. Often the interface domain names called by development, testing and online environments are different. How can we make the distinction? That is using environment variables and patterns.

Detailed graphic explanation of how to integrate the Ace code editor in a Vue project Detailed graphic explanation of how to integrate the Ace code editor in a Vue project Apr 24, 2023 am 10:52 AM

Ace is an embeddable code editor written in JavaScript. It matches the functionality and performance of native editors like Sublime, Vim, and TextMate. It can be easily embedded into any web page and JavaScript application. Ace is maintained as the main editor for the Cloud9 IDE and is the successor to the Mozilla Skywriter (Bespin) project.

Explore how to write unit tests in Vue3 Explore how to write unit tests in Vue3 Apr 25, 2023 pm 07:41 PM

Vue.js has become a very popular framework in front-end development today. As Vue.js continues to evolve, unit testing is becoming more and more important. Today we’ll explore how to write unit tests in Vue.js 3 and provide some best practices and common problems and solutions.

Let's talk in depth about reactive() in vue3 Let's talk in depth about reactive() in vue3 Jan 06, 2023 pm 09:21 PM

Foreword: In the development of vue3, reactive provides a method to implement responsive data. This is a frequently used API in daily development. In this article, the author will explore its internal operating mechanism.

VUE3 quick start: using Vue.js instructions to switch tabs VUE3 quick start: using Vue.js instructions to switch tabs Jun 15, 2023 pm 11:45 PM

This article aims to help beginners quickly get started with Vue.js3 and achieve a simple tab switching effect. Vue.js is a popular JavaScript framework that can be used to build reusable components, easily manage the state of your application, and handle user interface interactions. Vue.js3 is the latest version of the framework. Compared with previous versions, it has undergone major changes, but the basic principles have not changed. In this article, we will use Vue.js instructions to implement the tab switching effect, with the purpose of making readers familiar with Vue.js

A simple comparison of JSX syntax and template syntax in Vue (analysis of advantages and disadvantages) A simple comparison of JSX syntax and template syntax in Vue (analysis of advantages and disadvantages) Mar 23, 2023 pm 07:53 PM

In Vue.js, developers can use two different syntaxes to create user interfaces: JSX syntax and template syntax. Both syntaxes have their own advantages and disadvantages. Let’s discuss their differences, advantages and disadvantages.

Analyze the principle of Vue2 implementing composition API Analyze the principle of Vue2 implementing composition API Jan 13, 2023 am 08:30 AM

Since the release of Vue3, the word composition API has entered the field of vision of students who write Vue. I believe everyone has always heard how much better the composition API is than the previous options API. Now, due to the release of the @vue/composition-api plug-in, Vue2 Students can also get on the bus. Next, we will mainly use responsive ref and reactive to conduct an in-depth analysis of how this plug-in achieves this.

See all articles