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)

Karen Carpenter
Karen Carpenter forward
2022-01-26 18:01:33 2390browse

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.

Message: {{ msg }} {{firstName}}{{lastName}} {{firstName+lastName}} {{firstName+""+lastName}} //使用 JavaScript 表达式 

{{counter*2}}

{{ number + 1 }}

{{ ok ? 'YES' : 'NO' }}

{{ message.split('').reverse().join('') }}

Instruction

  • v-once: Perform one-time interpolation. When the data changes, the content at the interpolation will not be updated
这个将不会改变: {{ msg }}
  • 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

{{message}}

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

{{message}}

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

百度

2, class binding

Object syntax

We can passv-bind:classan object to dynamically switch classes

The above syntax indicates thatactiveThis class exists and Whether or not will depend on the truthiness of data propertyisActive.
You can pass more fields in the object to dynamically switch between multiple classes. Additionally, thev-bind:classdirective can also coexist with ordinary class attributes.

data: { isActive: true, hasError: false}

The result is rendered as:

WhenisActiveorhasErrorchanges, the class list will be updated accordingly. For example, ifhasErrorevaluates totrue, 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

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.

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

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:

data: { activeClass: 'active', errorClass: 'text-danger' }

Rendered as:

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

Writing like this will always AdderrorClass, but only addactiveClassifisActiveis 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:

3. Style binding inline style

Object syntax
# The object syntax of ##v-bind:styleis 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):

data: { activeColor: 'red', fontSize: 30 }
It is usually better to bind directly to a style object, which will make Templates are clearer:

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

//计算属性

//方法

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

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.

{{ message.split('').reverse().join('') }}

Basic example

Original message: "{{ message }}"

Computed reversed message: "{{ reversedMessage }}"

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 propertyvm.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.reversedMessagealways depends on the value ofvm.message.You can bind computed properties in templates just like normal properties. Vue knows that
vm.reversedMessagedepends onvm.message, so whenvm.messagechanges, all dependencies onvm.reversedMessageBindings 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, andvm.firstNameandvm.lastNamewill be updated accordingly.

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

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

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

Reversed message: "{{ reversedMessage() }}"

// 在组件中

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

计算属性 vs 侦听属性

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

{{ fullName }}

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

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还可以接收一个需要调用的方法名称

The button above has been clicked {{ counter }} times.

参数问题(括号问题)

1、无参

  

2、有参

   

只需要event对象时,

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

 

几种错误写法

 

事件修饰符

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

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

   
...
...
...

1.事件修饰符

  • .stop 阻止事件冒泡,调用event.stopPropagation
 
  • .prevent 阻止事件默认行为,调用event.preventDefault()
     
  • .self 事件绑定的元素本身触发时才触发回调
  
...
  • .once 事件只能触发一次,第二次就不会触发了

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

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

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

   
...
  • .capture
  
...

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

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

5、条件渲染

基础

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

Vue is awesome!

isShow为false时显示