曾 俊

曾 俊

1660788000

理解 Vue 中的观察者

Vue 被设计为可动态扩展的,允许您快速开发可重用和可维护的组件,使用客户端数据绑定,并提供丰富的插件生态系统来增强其功能。

Vue 中可用的众多功能之一是 watcher 功能,它允许我们监视应用程序状态并根据这些更改触发操作。在本文中,我们将了解观察者在 Vue 中是如何工作的,它们可以做什么,以及如何利用它们来构建强大的应用程序。

什么是观察者?

Vue 中的观察者是一个特殊的功能,它允许我们观察一些数据并在数据发生变化时执行特定的操作。这是一种更通用的方式来观察和响应 Vue 实例中的数据变化。

有了观察者,我们不仅可以观察属性并执行自定义操作;我们还可以访问此特定属性正在更改的旧值,以及它已更改为的新值。

使用观察者

使用 Options API,我们可以利用 watch 选项来监听属性值的变化,如下所示:

<script>
export default {
  data() {
    return {
      message: "Hello Vue!",
    };
  },
  watch: {
    message(newValue, oldValue) {
      // do something with newValue and oldValue.
    },
  },
};
</script>

此外,我们还可以使用Composition APIwatch()功能来完成同样的事情:

<script setup>
import { ref, watch } from "vue";
const message = ref("Hello Vue!");

watch(message, (newValue, oldValue) => {
  // do something with newValue and oldValue.
});
</script>

因此,只要值发生message变化,我们就能够访问其新值或先前值并执行任何首选操作。

在随后的章节中,我们将研究在实际应用程序中使用观察者的更多实际示例。然而,在我们到达那里之前,让我们回顾一下观察者可用的所有选项。

使用选项进行深度观看deep

Vue.js 中观察者的默认行为是肤浅的;即,它们仅监视顶层数据的更改,并且不会对嵌套的属性更改做出反应。

例如,我们有一个对象数组:

<script>
export default {
  data() {
    return {
      someData: [
        {
          id: 1,
          name: "John",
        },
        {
          id: 2,
          name: "Jane",
        },
      ],
    };
  },
  watch: {
    someData(newValue, oldValue) {
      console.log("someData changed!");
    },
  },
};
</script>

…并像我们上面所做的那样为这些数据设置一个观察者。当对象的属性发生变化时,例如当我们设置someData[0].id为随机数时,我们的观察者将不会被触发。

deep我们可以通过在我们的观察者中设置一个可选属性来解决这个问题true。但是,这将稍微改变创建观察者的语法,因为我们必须引入一个新的处理函数:

// . . .
watch: {
  someData: {
    handler(newValue, oldValue) {
      // console.log(newValue, oldValue);
      console.log("someData changed!");
    },
    deep: true,
  },
},

有了这个新增功能,即使嵌套属性发生变化,我们的观察者也会被触发。

此示例也可以使用watch()Vue 3 组合 API 中的函数复制,如下所示:

<script setup>
import { ref, watch } from "vue";

const someData = ref([
  {
    id: 1,
    name: "John",
  },
  {
    id: 2,
    name: "Jane",
  },
]);

watch(someData, (newValue, oldValue) => {
    console.log("someData changed!");
  },
  {
    deep: true,
  }
);
</script>

选项_immediate

除非您正在观看的值已更改,否则不会立即激活观察者。但在某些情况下,我们可能希望使用我们正在观察的属性的初始值执行某些操作。例如,我们的应用程序可能要求我们发送一个包含初始数据的 API 请求,然后如果数据发生变化则重复该过程。

我们可以像在前面的示例中那样使用处理函数来强制观察者立即执行,并将其immediate选项设置为true

<script>
export default {
  data() {
    return {
      message: "Hello Vue.js!",
    };
  },
  watch: {
    message: {
      handler(val) {
        console.log(val);
      },
      immediate: true,
    },
  },
};
</script>

通过这样做,我们可以让我们的观察者在我们的应用程序启动后立即采取某种行动,并在我们正在观察的属性在未来发生变化时继续这样做。

使用 Vue 3,immediate还可以将选项添加到可选对象中,如下所示:

<脚本设置> import { ref, watch } from "vue"; const message = ref("Hello Vue!"); 观看(消息,(newValue)=> { console.log(newValue);},{立即:真,});</脚本>

此外,Composition API 引入了一种新方法,该方法与将 immediate 选项设置watchEffect()为 非常相似。然而,虽然函数/选项只跟踪显式监控的源,但会自动跟踪在其执行过程中访问的每个反应属性:watch()truewatchwatchEffect()

<script setup>
import { ref, watchEffect } from "vue";
const foo = ref("Hello world!");
const bar = ref("Hello again!");

watchEffect(() => {
  console.log(foo.value);
  console.log(bar.value);
});
</script>

foo以这种方式,和的初始值bar被记录到控制台,并且将在它们的值发生变化时继续被记录。

观察者的示例场景

为了进一步了解观察者在现实生活中的应用程序是如何工作的,让我们看一些实际的例子。

观看打字状态

一个简单直观的观察者实验是一个应用程序,它观察输入状态并在用户输入时执行某些操作:

<template>
  <div>
    <input type="text" v-model="message" />
    <p v-if="typing">Typing...</p>
  </div>
</template>

<script setup>
import { ref, watch } from "vue";

const message = ref("");
const typing = ref(false);

watch(message, (value) => {
  typing.value = true;
  setTimeout(() => {
    typing.value = false;
  }, 2000);
});
</script>

在这个例子中,我们创建了两个反应状态(messagetyping)。然后我们将 绑定message到一个输入元素并为它创建一个观察者,这样每当它发生变化时,我们将typing值设置为falseto并在 2 秒后true自动将其设置回。false

当我们在浏览器中运行这个例子时,我们会得到以下结果:

你好世界

虽然此示例是基本示例,但您可以更进一步,向远程 API 发送请求并根据此请求的响应更新您的标记,类似于 Google 等搜索引擎在您键入时提供搜索建议的方式。

实时转换器

另一个交互式示例是一个简单的转换器应用程序,其中可以根据不同的输入点影响和计算输出。

就像下面的代码一样,我们创建了一个温度转换器,其中华氏值可以通过输入摄氏度值来计算,反之亦然:

<template>
  <div class="centered">
    <div>
      <label for="celsius">Degree in celsius</label>
      <input type="text" v-model="tempCelsius" id="celsius" />
    </div>
    <p style="font-size: 30px; margin: 0; font-weight: 600">=</p>
    <div>
      <label for="fahrenheit">Degree in fahrenheit</label>
      <input type="text" v-model="tempFahrenheit" id="fahrenheit" />
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from "vue";

const tempCelsius = ref(null);
const tempFahrenheit = ref(null);

watch(tempCelsius, (newValue) => {
  tempFahrenheit.value = Math.round((newValue * 9) / 5 + 32);
});

watch(tempFahrenheit, (newValue) => {
  tempCelsius.value = Math.round(((newValue - 32) * 5) / 9);
});
</script>

运行它也会给我们下面的输出:

温度转换器

简单的倒计时

为了查看该watchEffect()功能的实际效果,我们还在下面创建了一个简单的倒计时计时器应用程序,它将在我们的应用程序安装后 10 秒开始计数,并在计时器达到 5 秒时结束:

<template>
  <div class="centered">
    <h1>{{ counter }}</h1>
  </div>
</template>

<script setup>
import { ref, watchEffect } from "vue";
const counter = ref(10);

watchEffect(() => {
  if (counter.value > 5) {
    setTimeout(() => {
      counter.value--;
    }, 1000);
  }
});
</script>

这背后的逻辑非常简单。我们创建了counter一个值为 10 的反应属性。然后我们创建了一个watchEffect()将每秒连续减少 1 的计数器,并在其值为 5 时停止。

停止观察者

当父组件卸载时,watcher 会自动停止,并且在大多数情况下,您不需要手动结束 watcher。但是,在某些情况下,您可能想要停止观察者,可能是在满足条件时,这样做非常简单。

使用 Composition API,我们只需将观察者分配给自定义变量,然后调用此变量来停止观察者,如下所示:

const unwatch = watch(foo, (value) => {
  // ...
});

// stop watcher
unwatch();

同样也适用watchEffect()。然而,使用 Options API,我们只能以编程方式停止观察者,如果它是使用this.$watch()方法创建的,而不是通过观察者选项创建的:

<script>
export default {
  data() {
    return {
      foo: null,
    };
  },
  created() {
    const unwatch = this.$watch("foo", (value) => {
      console.log(value);
    });

    setTimeout(() => {
      unwatch();
    }, 5000);
  },
};
</script>

在这个例子中,我们在应用的 created 钩子中建立了一个新的 watcher,5 秒后,我们停止了 watcher。

计算属性与观察者

关于何时使用计算属性以及何时使用观察者存在很多不确定性。尽管如此,本节可以澄清这种情况。

计算属性用于根据其他一些条件计算属性的值。另一方面,观察者主要不用于更改属性的值;相反,它们用于在值发生更改时通知您,并让您根据这些更改执行某些操作。

当您需要获取对象的当前值并在逻辑中使用它时,应该使用计算属性,例如基于它计算某些东西。当您需要知道一个或多个值何时发生变化并做出相应反应时,应该使用观察者。

结论

观察者是 Vue 中的一个强大功能。它们使我们能够对系统中的变化立即做出动态反应。

如果一个观察者被添加到一个元素中,任何时候它发生变化,我们都可以对这个变化采取行动。虽然这看起来像是一个极端情况,但它是一个很好的例子,说明了能够对变化做出反应如何是有用的。在本文中,我们能够详细介绍如何使用观察者及其可用选项。此外,我们还研究了如何在实际应用程序中使用观察者的各种实际示例。

来源:https ://blog.logrocket.com/understanding-watchers-vue/

#vue 

What is GEEK

Buddha Community

理解 Vue 中的观察者
Luna  Mosciski

Luna Mosciski

1600583123

8 Popular Websites That Use The Vue.JS Framework

In this article, we are going to list out the most popular websites using Vue JS as their frontend framework.

Vue JS is one of those elite progressive JavaScript frameworks that has huge demand in the web development industry. Many popular websites are developed using Vue in their frontend development because of its imperative features.

This framework was created by Evan You and still it is maintained by his private team members. Vue is of course an open-source framework which is based on MVVM concept (Model-view view-Model) and used extensively in building sublime user-interfaces and also considered a prime choice for developing single-page heavy applications.

Released in February 2014, Vue JS has gained 64,828 stars on Github, making it very popular in recent times.

Evan used Angular JS on many operations while working for Google and integrated many features in Vue to cover the flaws of Angular.

“I figured, what if I could just extract the part that I really liked about Angular and build something really lightweight." - Evan You

#vuejs #vue #vue-with-laravel #vue-top-story #vue-3 #build-vue-frontend #vue-in-laravel #vue.js

Teresa  Bosco

Teresa Bosco

1598685221

Vue File Upload Using vue-dropzone Tutorial

In this tutorial, I will show you how to upload a file in Vue using vue-dropzone library. For this example, I am using Vue.js 3.0. First, we will install the Vue.js using Vue CLI, and then we install the vue-dropzone library. Then configure it, and we are ready to accept the file. DropzoneJS is an open source library that provides drag and drops file uploads with image previews. DropzoneJS is lightweight doesn’t depend on any other library (like jQuery) and is  highly customizable. The  vue-dropzone is a vue component implemented on top of Dropzone.js. Let us start Vue File Upload Using vue-dropzone Tutorial.

Vue File Upload Using vue-dropzone

First, install the Vue using Vue CLI.

#vue #vue-dropzone #vue.js #dropzone.js #dropzonejs #vue cli

Aria Barnes

Aria Barnes

1625232484

Why is Vue JS the most Preferred Choice for Responsive Web Application Development?

For more than two decades, JavaScript has facilitated businesses to develop responsive web applications for their customers. Used both client and server-side, JavaScript enables you to bring dynamics to pages through expanded functionality and real-time modifications.

Did you know!

According to a web development survey 2020, JavaScript is the most used language for the 8th year, with 67.7% of people choosing it. With this came up several javascript frameworks for frontend, backend development, or even testing.

And one such framework is Vue.Js. It is used to build simple projects and can also be advanced to create sophisticated apps using state-of-the-art tools. Beyond that, some other solid reasons give Vuejs a thumbs up for responsive web application development.

Want to know them? Then follow this blog until the end. Through this article, I will describe all the reasons and benefits of Vue js development. So, stay tuned.

Vue.Js - A Brief Introduction

Released in the year 2014 for public use, Vue.Js is an open-source JavaScript framework used to create UIs and single-page applications. It has over 77.4 million likes on Github for creating intuitive web interfaces.

The recent version is Vue.js 2.6, and is the second most preferred framework according to Stack Overflow Developer Survey 2019.

Every Vue.js development company is widely using the framework across the world for responsive web application development. It is centered around the view layer, provides a lot of functionality for the view layer, and builds single-page web applications.

Some most astonishing stats about Vue.Js:

• Vue was ranked #2 in the Front End JavaScript Framework rankings in the State of JS 2019 survey by developers.

• Approximately 427k to 693k sites are built with Vue js, according to Wappalyzer and BuiltWith statistics of June 2020.

• According to the State of JS 2019 survey, 40.5% of JavaScript developers are currently using Vue, while 34.5% have shown keen interest in using it in the future.

• In Stack Overflow's Developer Survey 2020, Vue was ranked the 3rd most popular front-end JavaScript framework.

Why is Vue.Js so popular?

• High-speed run-time performance
• Vue.Js uses a virtual DOM.
• The main focus is on the core library, while the collaborating libraries handle other features such as global state management and routing.
• Vue.JS provides responsive visual components.

Top 7 Reasons to Choose Vue JS for Web Application Development

Vue js development has certain benefits, which will encourage you to use it in your projects. For example, Vue.js is similar to Angular and React in many aspects, and it continues to enjoy increasing popularity compared to other frameworks.

The framework is only 20 kilobytes in size, making it easy for you to download files instantly. Vue.js easily beats other frameworks when it comes to loading times and usage.

Take a look at the compelling advantages of using Vue.Js for web app development.

#1 Simple Integration

Vue.Js is popular because it allows you to integrate Vue.js into other frameworks such as React, enabling you to customize the project as per your needs and requirements.

It helps you build apps with Vue.js from scratch and introduce Vue.js elements into their existing apps. Due to its ease of integration, Vue.js is becoming a popular choice for web development as it can be used with various existing web applications.

You can feel free to include Vue.js CDN and start using it. Most third-party Vue components and libraries are additionally accessible and supported with the Vue.js CDN.

You don't need to set up node and npm to start using Vue.js. This implies that it helps develop new web applications, just like modifying previous applications.

The diversity of components allows you to create different types of web applications and replace existing frameworks. In addition, you can also choose to hire Vue js developers to use the technology to experiment with many other JavaScript applications.

#2 Easy to Understand

One of the main reasons for the growing popularity of Vue.Js is that the framework is straightforward to understand for individuals. This means that you can easily add Vue.Js to your web projects.

Also, Vue.Js has a well-defined architecture for storing your data with life-cycle and custom methods. Vue.Js also provides additional features such as watchers, directives, and computed properties, making it extremely easy to build modern apps and web applications with ease.

Another significant advantage of using the Vue.Js framework is that it makes it easy to build small and large-scale web applications in the shortest amount of time.

#3 Well-defined Ecosystem

The VueJS ecosystem is vibrant and well-defined, allowing Vue.Js development company to switch users to VueJS over other frameworks for web app development.

Without spending hours, you can easily find solutions to your problems. Furthermore, VueJs lets you choose only the building blocks you need.

Although the main focus of Vue is the view layer, with the help of Vue Router, Vue Test Utils, Vuex, and Vue CLI, you can find solutions and recommendations for frequently occurring problems.

The problems fall into these categories, and hence it becomes easy for programmers to get started with coding right away and not waste time figuring out how to use these tools.

The Vue ecosystem is easy to customize and scales between a library and a framework. Compared to other frameworks, its development speed is excellent, and it can also integrate different projects. This is the reason why most website development companies also prefer the Vue.Js ecosystem over others.

#4 Flexibility

Another benefit of going with Vue.Js for web app development needs is flexibility. Vue.Js provides an excellent level of flexibility. And makes it easier for web app development companies to write their templates in HTML, JavaScript, or pure JavaScript using virtual nodes.

Another significant benefit of using Vue.Js is that it makes it easier for developers to work with tools like templating engines, CSS preprocessors, and type checking tools like TypeScript.

#5 Two-Way Communication

Vue.Js is an excellent option for you because it encourages two-way communication. This has become possible with the MVVM architecture to handle HTML blocks. In this way, Vue.Js is very similar to Angular.Js, making it easier to handle HTML blocks as well.

With Vue.Js, two-way data binding is straightforward. This means that any changes made by the developer to the UI are passed to the data, and the changes made to the data are reflected in the UI.

This is also one reason why Vue.Js is also known as reactive because it can react to changes made to the data. This sets it apart from other libraries such as React.Js, which are designed to support only one-way communication.

#6 Detailed Documentation

One essential thing is well-defined documentation that helps you understand the required mechanism and build your application with ease. It shows all the options offered by the framework and related best practice examples.

Vue has excellent docs, and its API references are one of the best in the industry. They are well written, clear, and accessible in dealing with everything you need to know to build a Vue application.

Besides, the documentation at Vue.js is constantly improved and updated. It also includes a simple introductory guide and an excellent overview of the API. Perhaps, this is one of the most detailed documentation available for this type of language.

#7 Large Community Support

Support for the platform is impressive. In 2018, support continued to impress as every question was answered diligently. Over 6,200 problems were solved with an average resolution time of just six hours.

To support the community, there are frequent release cycles of updated information. Furthermore, the community continues to grow and develop with backend support from developers.



Wrapping Up

VueJS is an incredible choice for responsive web app development. Since it is lightweight and user-friendly, it builds a fast and integrated web application. The capabilities and potential of VueJS for web app development are extensive.

While Vuejs is simple to get started with, using it to build scalable web apps requires professionalism. Hence, you can approach a top Vue js development company in India to develop high-performing web apps.

Equipped with all the above features, it doesn't matter whether you want to build a small concept app or a full-fledged web app; Vue.Js is the most performant you can rely on.

Original source

 

#vue js development company #vue js development company in india #vue js development company india #vue js development services #vue js development #vue js development companies

Sofia Kelly

Sofia Kelly

1578061020

10 Best Vue Icon Component For Your Vue.js App

Icons are the vital element of the user interface of the product enabling successful and effective interaction with it. In this article, I will collect 10 Vue icon component to bring more interactivity, better UI design to your Vue application.

1. Animated SweetAlert Icons for Vue

A clean and simple Vue wrapper for SweetAlert’s fantastic status icons. This wrapper is intended for users who are interested in just the icons. For the standard SweetAlert modal with all of its bells and whistles, you should probably use Vue-SweetAlert 2

Animated SweetAlert Icons for Vue

Demo: https://vue-sweetalert-icons.netlify.com/

Download: https://github.com/JorgenVatle/vue-sweetalert-icons/archive/master.zip

2. vue-svg-transition

Create 2-state, SVG-powered animated icons.

vue-svg-transition

Demo: https://codesandbox.io/s/6v20q76xwr

Download: https://github.com/kai-oswald/vue-svg-transition/archive/master.zip

3. Vue-Awesome

Awesome SVG icon component for Vue.js, with built-in Font Awesome icons.

Vue-Awesome

Demo: https://justineo.github.io/vue-awesome/demo/

Download: https://github.com/Justineo/vue-awesome/archive/master.zip

4. vue-transitioning-result-icon

Transitioning Result Icon for Vue.js

A scalable result icon (SVG) that transitions the state change, that is the SVG shape change is transitioned as well as the color. Demonstration can be found here.

A transitioning (color and SVG) result icon (error or success) for Vue.

vue-transitioning-result-icon

Demo: https://transitioning-result-icon.dexmo-hq.com/

Download: https://github.com/dexmo007/vue-transitioning-result-icon/archive/master.zip

5. vue-zondicons

Easily add Zondicon icons to your vue web project.

vue-zondicons

Demo: http://www.zondicons.com/icons.html

Download: https://github.com/TerryMooreII/vue-zondicons/archive/master.zip

6. vicon

Vicon is an simple iconfont componenet for vue.

iconfont
iconfont is a Vector Icon Management & Communication Platform made by Alimama MUX.

vicon

Download: https://github.com/Lt0/vicon/archive/master.zip

7. vue-svgicon

A tool to create svg icon components. (vue 2.x)

vue-svgicon

Demo: https://mmf-fe.github.io/vue-svgicon/v3/

Download: https://github.com/MMF-FE/vue-svgicon/archive/master.zip

8. vue-material-design-icons

This library is a collection of Vue single-file components to render Material Design Icons, sourced from the MaterialDesign project. It also includes some CSS that helps make the scaling of the icons a little easier.

vue-material-design-icons

Demo: https://gitlab.com/robcresswell/vue-material-design-icons

Download: https://gitlab.com/robcresswell/vue-material-design-icons/tree/master

9. vue-ionicons

Vue Icon Set Components from Ionic Team

Design Icons, sourced from the Ionicons project.

vue-ionicons

Demo: https://mazipan.github.io/vue-ionicons/

Download: https://github.com/mazipan/vue-ionicons/archive/master.zip

10. vue-ico

Dead easy, Google Material Icons for Vue.

This package’s aim is to get icons into your Vue.js project as quick as possible, at the cost of all the bells and whistles.

vue-ico

Demo: https://material.io/resources/icons/?style=baseline

Download: https://github.com/paulcollett/vue-ico/archive/master.zip

I hope you like them!

#vue #vue-icon #icon-component #vue-js #vue-app

Henry Short

Henry Short

1578472348

7 Best Vue Highlight Component for Your Vue App

Vue highlight is often used to highlight text and syntax. Here are the 7 Vue highlight components I’ve collected.

1. vue-snippets

Vue3 Snippets, This extension adds Vue3 Code Snippets into Visual Studio Code.

vue-snippets

Download


2. vim-vue-plugin

Vim syntax and indent plugin for vue files

vim-vue-plugin

Download


3. vue-highlighter

Vue directive for highlight multiple istances of a word.

vue-highlighter

Download


4. vue-code-highlight

Beautiful code syntax highlighting as Vue.js component.

vue-code-highlight

Download


5. Vue Prism Editor

A dead simple code editor with syntax highlighting and line numbers. 7kb/gz

Features

  • Code Editing ^^
  • Syntax highlighting
  • Undo / Redo
  • Copy / Paste
  • The spaces/tabs of the previous line is preserved when a new line is added
  • Works on mobile (thanks to contenteditable)
  • Resize to parent width and height
  • Support for line numbers
  • Support for autosizing the editor
  • Autostyling the linenumbers(optional)

Vue Prism Editor

Demo

Download


6. vue-highlight-words

A simple port from react-highlight-words

Vue component to highlight words within a larger body of text.

vue-highlight-words

Demo

Download


7. vue-highlight-text

Vue component for highlight multiple istances of a word.

vue-highlight-text

Demo

Download


Thank for read!

#vue-highlight #vue #vue-highlight-component #highlight-vue