Home  >  Article  >  Web Front-end  >  Computed properties, event monitoring and conditional rendering of Vue basic syntax (organized and shared)

Computed properties, event monitoring and conditional rendering of Vue basic syntax (organized and shared)

WBOY
WBOYforward
2022-01-26 18:01:332394browse

This article summarizes the basic syntax of Vue, including calculated properties, event listening, conditional rendering, list rendering and other related issues. I hope it will be helpful to everyone.

Computed properties, event monitoring and conditional rendering of Vue basic syntax (organized and shared)

Vue Note 2: Basic Syntax

1. Interpolation (dynamic content)

Mustache syntax (double Braces)

Insert the text data in data into HTML. At this time, the data is responsive.

<span>Message: {{ msg }}</span>
<span>{{firstName}}{{lastName}}</span>
<span>{{firstName+lastName}}</span>
<span>{{firstName+""+lastName}}</span>
//使用 JavaScript 表达式
<h2> {{counter*2}}</h2>
<h2>{{ number + 1 }}</h2>
<h2>{{ ok ? 'YES' : 'NO' }}</h2>
<h2>{{ message.split('').reverse().join('') }}</h2>

Instruction

  • v-once: Perform one-time interpolation. When the data changes, the content at the interpolation will not be updated
<span v-once>这个将不会改变: {{ msg }}</span>
  • v-html: Parse html and display
  • v-text: Render the content text of the specified dom, similar to Mustache, generally not used, not flexible enough, and will cover all content in the tag
  • v- pre: Display the tag content intact without parsing
<h2 v-pre>{{message}} </h2>

Result: {{message}}

  • v-cloak: Solve vue parsing lag There will be a problem of {{}} flashing
    Before vue parsing, p has the attribute v-cloak, but after parsing it does not have this attribute.
    So you can use this command to hide the uncompiled Mustache tag until the instance is ready
  <p id="app" v-cloak>{{message}}</p>
  <style>
      [v-cloak]{ display:none; }
  </style>

2. Binding attributes (dynamic attributes)

v -bind is used to bind one or more property values, or pass props values ​​to another component. The abbreviation is colon:

1, src and href of the element

<img :src="ImgUrl" /><a :href="aHref">百度</a>

2, class binding

Object syntax

We can pass v-bind:class an object to dynamically switch classes

<p v-bind:class="{ active: isActive }"></p>

The above syntax indicates that active This class exists and Whether or not will depend on the truthiness of data property isActive.
You can pass more fields in the object to dynamically switch between multiple classes. Additionally, the v-bind:class directive can also coexist with ordinary class attributes.

<p class="static" v-bind:class="{ active: isActive, &#39;text-danger&#39;: hasError }"></p>
data: {
  isActive: true,
  hasError: false}

The result is rendered as:

<p class="static active"></p>

When isActive or hasError changes, the class list will be updated accordingly. For example, if hasError evaluates to true, the class list becomes "static active text-danger".
The bound data object does not have to be defined inline in the template, it can also be defined in data

<p v-bind:class="classObject"></p>data: {
  classObject: {
    active: true,
    'text-danger': false
  }
}

The rendering result is the same as above. We can also bind a computed property of the returned object here.

<p v-bind:class="classObject"></p>data: {
  isActive: true,
  error: null
},
computed: {
  classObject: function () {
    return {
      active: this.isActive && !this.error,
      'text-danger': this.error && this.error.type === 'fatal'
    }
  }
}

Methods that return objects

<p v-bind:class="IsActive()"></p>data: {
  isActive: true,
  error: null
},
methods: {
  IsActive() {
    return {
      active: this.isActive && !this.error,
      line:isLine
    }
  }
}

Array syntax

We can pass an array tov-bind:class , to apply a class list:

<p v-bind:class="[activeClass, errorClass]"></p>
data: {
  activeClass: 'active',
  errorClass: 'text-danger'
}

Rendered as:

<p class="active text-danger"></p>

To switch classes in the list according to conditions, you can use a ternary expression:

<p v-bind:class="[isActive ? activeClass : &#39;&#39;, errorClass]"></p>

Writing like this will always Add errorClass, but only add activeClass if isActive is truthy[1].

However, it is a bit cumbersome to write like this when there are multiple conditional classes. Therefore, object syntax can also be used in array syntax:

<p v-bind:class="[{ active: isActive }, errorClass]"></p>

3. Style binding inline style

Object syntax
# The object syntax of ##v-bind:style is very intuitive - it looks very like CSS, but it is actually a JavaScript object. CSS property names can be named in camelCase or kebab-case (remember to enclose them in quotes):

<p v-bind:style="{ color: activeColor, fontSize: fontSize + &#39;px&#39; }"></p> <!--数加字符串隐式转换为字符串类型 -->data: {
  activeColor: 'red',
  fontSize: 30
}
It is usually better to bind directly to a style object, which will make Templates are clearer:

<p v-bind:style="styleObject"></p>data: {
  styleObject: {
    color: 'red',
    fontSize: '13px'
  }
}
Similarly, object syntax is often used in conjunction with computed properties that return objects. Or the array syntax of method

<p v-bind:class="classObject"></p> //计算属性<p v-bind:class="classObject()"></p> //方法

v-bind:style can apply multiple style objects to the same element:

<p v-bind:style="[baseStyles, overridingStyles]"></p>

3. Calculated attributes

Putting too much logic in the template will make the template overweight and difficult to maintain. The data needs to be changed before displaying it.

<p id="example">   {{ message.split('').reverse().join('') }} </p>
Basic example

<p id="example">
  <p>Original message: "{{ message }}"</p>
  <p>Computed reversed message: "{{ reversedMessage }}"</p> <!--按照属性的样式给函数起名,引用函数名不用加括号--></p><script>var vm = new Vue({
  el: '#example',
  data: {
    message: 'Hello'
  },
  computed: {
    // 计算属性的 getter
    reversedMessage: function () {
      // `this` 指向 vm 实例
      return this.message.split('').reverse().join('')
    }
  }})</script>

Result:

Original message: “Hello”

Computed reversed message: “olleH”

Here We declare a computed property

reversedMessage. The function we provide will be used as the getter function of property vm.reversedMessage:

console.log(vm.reversedMessage) // => 'olleH'vm.message = 'Goodbye'console.log(vm.reversedMessage) // => 'eybdooG'
You can open the browser console and modify the vm in the example yourself. The value of

vm.reversedMessage always depends on the value of vm.message. You can bind computed properties in templates just like normal properties. Vue knows that
vm.reversedMessage depends on vm.message, so when vm.message changes, all dependencies on vm.reversedMessage Bindings are also updated. And the best part is that we've created this dependency declaratively: the computed property's getter function has no side effects, making it easier to test and understand.

Getters and setters of computed properties

Computed properties only have getters by default, which are read-only properties, but you can also provide a setter when needed:

// ...computed: {
  fullName: {
    // getter
    get: function () {
      return this.firstName + ' ' + this.lastName    },
    // setter
    set: function (newValue) {
      var names = newValue.split(' ')
      this.firstName = names[0]
      this.lastName = names[names.length - 1]
    }
  }}// ...
Run now When

vm.fullName = 'John Doe', the setter will be called, and vm.firstName and vm.lastName will be updated accordingly.

因为计算属性一般没有setter,所以简写为

 fullName:  function () {
      return this.firstName + ' ' + this.lastName }

计算属性 vs 方法
通过在表达式中调用方法也能达到同样的效果

<p>Reversed message: "{{ reversedMessage() }}"</p>// 在组件中<script>methods: {
  reversedMessage: function () {
    return this.message.split('').reverse().join('')
  }}</script>

两种方式的最终结果确实是完全相同的。然而,不同的是计算属性是基于它们的响应式依赖进行缓存的。只在相关响应式依赖发生改变时它们才会重新求值。这就意味着只要 message 还没有发生改变,多次访问 reversedMessage 计算属性会立即返回之前的计算结果,而不必再次执行函数。
这也同样意味着下面的计算属性将不再更新,相比之下,每当触发重新渲染时,调用方法将总会再次执行函数。

计算属性 vs 侦听属性

Vue 提供了一种更通用的方式来观察和响应 Vue 实例上的数据变动:侦听属性

<p id="demo">{{ fullName }}</p><script>
    var vm = new Vue({
        el: '#demo',
        data: {
            firstName: 'Foo',
            lastName: 'Bar',
            fullName: 'Foo Bar'
        },
        watch: {
            firstName: function (val) {
                this.fullName = val + ' ' + this.lastName            },
            lastName: function (val) {
                this.fullName = this.firstName + ' ' + val            }
        }</script>

上面代码是命令式且重复的。将它与计算属性的版本进行比较:

var vm = new Vue({
  el: '#demo',
  data: {
    firstName: 'Foo',
    lastName: 'Bar'
  },
  computed: {
    fullName: function () {
      return this.firstName + ' ' + this.lastName    }
  }})

计算属性传参

计算属性本身是不能传参的,但是可以通过闭包传参,但是传参之后没有缓存机制了,和methods没有什么区别,所以官网并没有介绍这个

 computed: {
	  usertype(){
		  return function (value){
			  var user = ''
			  value === 1 ? user = '学生' : user = '老师'
			  return user		  }
	  }
  }

4、事件监听

基础

可以用 v-on 指令监听 DOM 事件,并在触发时运行一些 JavaScript 代码。简写@click
许多事件处理逻辑会更为复杂,因此 v-on 还可以接收一个需要调用的方法名称

<p id="example-1">
    <button v-on:click="counter += 1">Add 1</button>
    <button v-on:click="increment"> + </button>
    <button v-on:click="decrement"> - </button>
    <p>The button above has been clicked {{ counter }} times.</p></p><script>
    var example1 = new Vue({
        el: '#example-1',
        data: {
            counter: 0
        },
      methods:{
        increment(){
          this.counter++
        },
        decrement(){
           this.counter--;
        }
      }
    })</script>

参数问题(括号问题)

1、无参

<!--()可有可无-->
<button v-on:click="greet">Greet</button>
<button v-on:click="greet()">Greet</button>

2、有参

<!--方法有参数,调用时没有传参数,但是加了(),形参默认为undefind-->
<button v-on:click="greet()">Greet</button> 
<!--方法有参数,调用时没有传参数,也不加(),返回浏览器产生的Event对象MouseEvent-->
<button v-on:click="greet">Greet</button>

只需要event对象时,

<button @click="btnClick(event)">111</button>

需要event对象,同时也需要其他对象时,可以用特殊变量 $event 把它传入方法:

<button @click="warn(&#39;Form cannot be submitted yet.&#39;, $event)">
  Submit
</button>
<script>
  methods: {
    warn: function (message, event) {
      // 现在我们可以访问原生事件对象
      if (event) {
        event.preventDefault()
      }
      alert(message)
    }
  }
</script>

几种错误写法

<button @click="warn">111</button><!--传的是event和undefined-->
<button @click="warn("111",event)">111</button><!--传的是"111"和undefined(报错,找不到event)-->

事件修饰符

在事件处理程序中调用 event.preventDefault()event.stopPropagation() 是非常常见的需求。尽管我们可以在方法中轻松实现这点,但更好的方式是:方法只有纯粹的数据逻辑,而不是去处理 DOM 事件细节。

为了解决这个问题,Vue.js 为 v-on 提供了事件修饰符。之前提过,修饰符是由点开头的指令后缀来表示的。

<!-- 阻止单击事件继续传播 -->
<a v-on:click.stop="doThis"></a>
  
<!-- 提交事件不再重载页面 -->
<form v-on:submit.prevent="onSubmit"></form>

<!-- 禁止蒙版下的页面滚动-->
<a v-on:touchmove.stop.prevent="doThat"></a> 

<!-- 添加事件监听器时使用事件捕获模式 -->
<!-- 即内部元素触发的事件先在此处理,然后才交由内部元素进行处理 -->
<div v-on:click.capture="doThis">...</div>

<!-- 只当在 event.target 是当前元素自身时触发处理函数 -->
<!-- 即事件不是从内部元素触发的 -->
<div v-on:click.self="doThat">...</div>

<!-- 滚动事件的默认行为 (即滚动行为) 将会立即触发 , 而不会等待 `onScroll` 完成, 这其中包含 `event.preventDefault()` 的情况 -->
<div v-on:scroll.passive="onScroll">...</div>

1.事件修饰符

  • .stop 阻止事件冒泡,调用event.stopPropagation
<!-- 阻止单击事件继续传播 --> 
<a v-on:click.stop="doThis"></a>
  • .prevent 阻止事件默认行为,调用event.preventDefault()
<!-- 提交事件不再重载页面 --><form v-on:submit.prevent="onSubmit"></form>
<!-- 修饰符可以串联 -->
<a v-on:click.stop.prevent="doThat"></a>
<!-- 禁止蒙版下的页面滚动-->
<a v-on:touchmove.stop.prevent="doThat"></a> 
<!-- 只有修饰符 -->
<form v-on:submit.prevent></form>
  • .self 事件绑定的元素本身触发时才触发回调
<!-- 只当在 event.target 是当前元素自身时触发处理函数 -->
<!-- 即事件不是从内部元素触发的 --> 
<div v-on:click.self="doThat">...</div>
  • .once 事件只能触发一次,第二次就不会触发了

不像其它只能对原生的 DOM 事件起作用的修饰符,.once 修饰符还能被用到自定义的组件事件上

  • .native 将一个vue组件变成一个普通的html,使其可以监听click等原生事件,监听组件的原生事件
<Tag @click.native="handleClick">ok</Tag>
  • .passive 能够提升移动端的性能。

不要.passive 和 .prevent 一起使用,因为 .prevent 将会被忽略,同时浏览器可能会向你展示一个警告。请记 住,.passive 会告诉浏览器你想阻止事件的默认行为。

<!-- 滚动事件的默认行为 (即滚动行为) 将会立即触发 -->
<!-- 而不会等待 `onScroll` 完成  -->
<!-- 这其中包含 `event.preventDefault()` 的情况 -->
<div v-on:scroll.passive="onScroll">...</div>
  • .capture
<!-- 添加事件监听器时使用事件捕获模式 --> 
<!-- 即内部元素触发的事件先在此处理,然后才交由内部元素进行处理 --> 
<div v-on:click.capture="doThis">...</div>

使用修饰符时,顺序很重要;相应的代码会以同样的顺序产生。因此,用 v-on:click.prevent.self 会阻止所有的点击,而 v-on:click.self.prevent 只会阻止对元素自身的点击。

不要.passive 和 .prevent 一起使用,因为 .prevent 将会被忽略,同时浏览器可能会向你展示一个警告。请记住,.passive 会告诉浏览器你不想阻止事件的默认行为。

5、条件渲染

基础

v-if 指令用于条件性地渲染一块内容。这块内容只会在指令的表达式返回 truthy 值的时候被渲染。

<h1 v-if="isShow">Vue is awesome!</h1>
<h1 v-else>isShow为false时显示</h1>

<template> 元素上使用 v-if 条件渲染分组

因为 v-if 是一个指令,所以必须将它添加到一个元素上。但是如果想切换多个元素呢?此时可以把一个 <template> 元素当做不可见的包裹元素,并在上面使用 v-if。最终的渲染结果将不包含 <template> 元素。

<template v-if="ok">
  <h1>Title</h1>
  <p>Paragraph 1</p>
  <p>Paragraph 2</p></template>

v-else-if不常用,用计算属性更好

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

类似于 v-elsev-else-if 也必须紧跟在带 v-if 或者 v-else-if 的元素之后。

key 管理可复用的元素

Vue 会尽可能高效地渲染元素,通常会复用已有元素而不是从头开始渲染。这么做除了使 Vue 变得非常快之外,还有其它一些好处。例如,如果你允许用户在不同的登录方式之间切换:

<template v-if="loginType === &#39;username&#39;">
  <label for="username">Username</label><!--点击label,指向的input获得焦点-->
  <input id="username" placeholder="Enter your username"></template><template v-else>
  <label for="email">Email</label>
  <input id="email" placeholder="Enter your email address"></template>

问题:那么在上面的代码中切换 loginType 将不会清除用户已经输入的内容。

原因:两个模板使用了相同的元素,虚拟DOM渲染时,出于性能考虑<input> 不会被替换掉仅仅是替换了它的 placeholder

解决:添加一个具有唯一值的 key attribute 即可,key不同,不会复用

<template v-if="loginType === &#39;username&#39;">
  <label>Username</label>
  <input placeholder="Enter your username" key="username-input"></template><template v-else>
  <label>Email</label>
  <input placeholder="Enter your email address" key="email-input"></template>

注意,<label> 元素仍然会被高效地复用,因为它们没有添加 key attribute。

v-show

另一个用于根据条件展示元素的选项是 v-show 指令。用法大致一样:

<h1 v-show="ok">Hello!</h1>

不同的是带有 v-show 的元素始终会被渲染并保留在 DOM 中。v-show 只是简单地切换元素的 CSS 属性display

注意,v-show 不支持 <template> 元素,也不支持 v-else

v-if vs v-show

v-if 是“真正”的条件渲染,因为它会确保在切换过程中条件块内的事件监听器和子组件适当地被销毁和重建。

v-if 也是惰性的:如果在初始渲染时条件为假,则什么也不做——直到条件第一次变为真时,才会开始渲染条件块。

相比之下,v-show 就简单得多——不管初始条件是什么,元素总是会被渲染,并且只是简单地基于 CSS 进行切换,当条件为false时,仅仅是将元素的display属性设置为none而已。

一般来说,v-if 有更高的切换开销,而 v-show 有更高的初始渲染开销。

因此,如果需要非常频繁地切换,则使用 v-show 较好;如果在运行时条件很少改变,则使用 v-if 较好。

不推荐同时使用 v-ifv-for。当 v-ifv-for 一起使用时,v-for 具有比 v-if 更高的优先级。

6、列表渲染

6.1 遍历数组

v-for 把一个数组对应为一组元素,v-for 指令需要使用 item in items 形式的特殊语法,其中 items 是源数据数组,而 item 则是被迭代的数组元素的别名

<ul id="example-1">
  <li v-for="item in items" :key="item.message">{{ item.message }}  </li></ul><script>var example1 = new Vue({
  el: '#example-1',
  data: {
    items: [
      { message: 'Foo' },
      { message: 'Bar' }
    ]
  }})</script>

结果:

  • Foo
  • Bar

v-for 块中,我们可以访问所有父作用域的 property。v-for 还支持一个可选的第二个参数,即当前项的索引index。

<ul id="example-2">
  <li v-for="(item, index) in items"> {{ parentMessage }} - {{ index }} - {{ item.message }} </li></ul><script>var example2 = new Vue({
  el: '#example-2',
  data: {
    parentMessage: 'Parent',
    items: [
      { message: 'Foo' },
      { message: 'Bar' }
    ]
  }})</script>

结果:

  • Parent - 0 - Foo
  • Parent - 1 - Bar

你也可以用 of 替代 in 作为分隔符,因为它更接近 JavaScript 迭代器的语法:

<p v-for="item of items"></p>

6.2 遍历对象

你也可以用 v-for 来遍历一个对象的 property。

<!--第一个参数为value--><ul id="v-for-object" class="demo">
  <li v-for="value in object"> {{ value }} </li></ul><!--第二个参数为键名key--><p v-for="(value, name) in object">
  {{ name }}: {{ value }}</p><!--第三个参数为索引index--><p v-for="(value, name, index) in object">
  {{ index }}. {{ name }}: {{ value }}</p><script>new Vue({
  el: '#v-for-object',
  data: {
    object: {
      title: 'How to do lists in Vue',
      author: 'Jane Doe',
      publishedAt: '2016-04-10'
    }
  }})</script>

结果:

  • How to do lists in Vue

  • Jane Doe

  • 2016-04-10

title: How to do lists in Vue

author: Jane Doe

publishedAt: 2016-04-10

\0. title: How to do lists in Vue

\1. author: Jane Doe

\2. publishedAt: 2016-04-10

在遍历对象时,会按 Object.keys() 的结果遍历,但是不能保证它的结果在不同的 JavaScript 引擎下都一致。

6.3 维护状态 (key属性)

当 Vue 正在更新使用 v-for 渲染的元素列表时,它默认使用“就地更新”的策略。如果数据项的顺序被改变,Vue 将不会移动 DOM 元素来匹配数据项的顺序,而是就地更新每个元素,并且确保它们在每个索引位置正确渲染(与虚拟DOM和Diff算法有关)。

这个默认的模式是高效的,但是只适用于不依赖子组件状态或临时 DOM 状态 (例如:表单输入值) 的列表渲染输出

为了给 Vue 一个提示,以便它能跟踪每个节点的身份,从而重用和重新排序现有元素,你需要为每项提供一个唯一 key attribute:

<p v-for="item in items" v-bind:key="item.id">
  <!-- 内容 --></p>

建议尽可能在使用 v-for 时提供 key attribute,除非遍历输出的 DOM 内容非常简单,或者是刻意依赖默认行为以获取性能上的提升。因为它是 Vue 识别节点的一个通用机制,key 并不仅与 v-for 特别关联。

不要使用对象或数组之类的非基本类型值作为 v-forkey,请用字符串或数值类型的值。

6.4 数组更新检测

变更方法(数组的哪些方法是响应式的)

变更方法会变更调用了这些方法的原始数组

Vue 将被侦听的数组的变更方法进行了包裹,所以它们也将会触发视图更新。这些被包裹过的方法包括:

  • push() 加元素,this.names.push("aaa","bbb")

  • pop() 删除数组最后一个元素 ,names.pop()

  • shift()删除数组第一个元素

  • unshift()数组最前面添加元素

  • splice()删除/插入/替换元素

    第一个参数为从哪个位置开始删除/插入/替换元素

    删除元素:第二个参数传入要删除几个元素,不传则删除后面所有元素splice(0,2)

    替换元素:第二个元素传入要替换几个元素,后面跟用于替换的元素splice(0,2,’d’,'2')

    插入元素:第二个元素传入0,后面跟要插入的元素splice(0,0,’d’)

  • sort()数组排序

  • reverse()翻转数组

替换数组(高阶函数filter、map、reduce)

非变更方法,例如 filter()concat()slice()。它们不会变更原始数组,而总是返回一个新数组。你可能认为这将导致 Vue 丢弃现有 DOM 并重新渲染整个列表。幸运的是,事实并非如此。Vue 为了使得 DOM 元素得到最大范围的重用而实现了一些智能的启发式方法,所以用一个含有相同元素的数组去替换原来的数组是非常高效的操作。

由于 JavaScript 的限制,Vue 不能检测数组和对象的变化。深入响应式原理中有相关的讨论。

filter()显示过滤/排序后的结果

回调函数必须返回一个boolean值:

返回true时,函数内部会自动将这次回调的n加入到新的数组;返回false时,函数内部将过滤掉这次的n。

有时,我们想要显示一个数组经过过滤或排序后的版本,而不实际变更或重置原始数据。在这种情况下,可以创建一个计算属性,来返回过滤或排序后的数组。例如:

<li v-for="n in evenNumbers">{{ n }}</li>
<script>
data: {
  numbers: [ 1, 2, 3, 4, 5 ]
},
computed: {
  evenNumbers: function () {
    return this.numbers.filter(function (number) {
      return number % 2 === 0
    })
  }
}
</script>

在计算属性不适用的情况下 (例如,在嵌套 v-for 循环中) 你可以使用一个方法:

<ul v-for="set in sets">
  <li v-for="n in even(set)">{{ n }}</li>
</ul>
<script>
data: {
  sets: [[ 1, 2, 3, 4, 5 ], [6, 7, 8, 9, 10]]
},
methods: {
  even: function (numbers) {
    return numbers.filter(function (number) {
      return number % 2 === 0
    })
  }
}
</script>

map() 映射

let nums=[ 1, 2, 3, 4, 5 ]let nuwnums=nums.map(function(n){
    return n*2})

reduce 数组内元素的汇总

let nums=[ 1, 2, 3, 4, 5 ]//preValue为前一个值,0为初始默认值;n为数组内元素let nuwnums=nums.reduce(function(preValue,n){
    return preValue+n},0)

[在 v-for 里使用值范围]

v-for 也可以接受整数。在这种情况下,它会把模板重复对应次数。

<p>
  <span v-for="n in 10">{{ n }} </span>
</p>

结果:

1 2 3 4 5 6 7 8 9 10

<template>上使用 v-for

类似于 v-if,你也可以利用带有 v-for<template> 来循环渲染一段包含多个元素的内容。比如:

<ul>
  <template v-for="item in items">
    <li>{{ item.msg }}</li>
    <li class="pider" role="presentation"></li>
  </template>
</ul>

v-forv-if 一同使用

注意我们推荐在同一元素上使用 v-ifv-for

当它们处于同一节点,v-for 的优先级比 v-if 更高,这意味着 v-if 将分别重复运行于每个 v-for 循环中。

7、表单输入绑定v-model

基础使用

实现表单元素和数据的双向绑定

<input v-model="message" placeholder="edit me"><p>Message is: {{ message }}</p>data:{
	message:''
}

原理

<input type="text" :value="message" @input="valueChange" /><p>Message is: {{ message }}</p><script>
  data:{
    message:''
  },
	methods:{
     valueChange(event){
       this.message=$event.target.value;
     }
  }      </script>

简写:

<input type="text" :value="message" @input="message=$event.target.value" >

v-model 在内部为不同的输入元素使用不同的 property 并抛出不同的事件:

  • text 和 textarea 元素使用 value property 和 input 事件;
  • checkbox 和 radio 使用 checked property 和 change 事件;
  • select 字段将 value 作为 prop 并将 change 作为事件。

radio单选框

<label for="male">
	<input type="radio" id="male" value="男" v-model="sex">男</label><label for="female">
	<input type="radio" id="female" value="女" v-model="sex">女</label><h2>您选择的性别是{{sex}}</h2>data:{sex:'女'}

data中的sex为默认值,其单选按钮因为双向绑定也会默认选中

单选按钮的互斥:v-model 或者 name=“sex” 放在一个组内

checkbox复选框

单个勾选框,绑定到Boolean值

<label for="agree">
	<input type="checkbox" id="agree" v-model="isAgree">同意协议</label><h2>是否同意协议{{isAgree}}</h2><button :disabeled="!isAgree">
  下一步</button>data:{isAgree:false}

多选框,绑定到数组

<input type="checkbox"  v-model="hobbies">篮球<input type="checkbox"  v-model="hobbies">足球
data:{hobbies:[]}

select选择框

单选

<select v-model="fruit">
  <option value="apple">苹果</option>
  <option value="bannner">香蕉</option></select><h2>选择的水果是{{fruit}}</h2>data:{fruit:''}

多选

<select v-model="fruits" multiple>
  <option value="apple">苹果</option>
  <option value="bannner">香蕉</option></select><h2>选择的水果是{{fruits}}</h2>data:{fruits:[]}

修饰符

.lazy 在输入框输入完内容,光标离开时才更新视图
.trim 过滤首尾空格
.number 自动将用户的输入值转为数值类型。如果先输入数字,那它就会限制你输入的只能是数字;如果先输入字符串,那就相当于没有加.number

用法如下:

<input type="text" v-model.trim="value">

还有很多修饰符比如键盘,鼠标等修饰符

相关推荐:vue.js视频教程

The above is the detailed content of Computed properties, event monitoring and conditional rendering of Vue basic syntax (organized and shared). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete