
除了 JS 已有的功能外,Vue还具有自己独特的作用域级别。作用域控制可以使用哪些变量以及在何处使用。它控制它们对应用程序的不同部分的“可见性”。
了解 Vue 提供的作用域级别之间的差异会帮助我们编写更清晰的代码。
下面是 vue 中4个级别的作用域:
- 全局作用域
- 子树作用域
- 组件作用域
- 实例作用域
来看看这些作用域分别是什么。
全局作用域
Vue 应用程序中的全局作用域与任何编程语言中的全局作用域类似,这些变量在应用程序中的任何地方都是可用的。
可以把全局作用域看作应用程序作用域,因为它将作用域限制为整个应用程序。
使用全局作用域
使用全局作用域的主要方式是向Vue原型添加一个值:
Vue.prototype.$globalValue = 'Global Scope!';
通过将其添加到 Vue 对象的原型中,可以在应用程序的每个组件上自动使用它。可以像这样直接从组件访问它:
export default {
mounted() {
console.log(this.$globalValue); // 'Global Scope!'
},
};使用$作为这些变量的前缀是一种标准做法,因此我们知道它们是全局值,而不是每个组件唯一的。
Vue、vue-router和vuex(以及许多其他库)都使用这种技术来定义全局值。例如,来自vue-router的$route对象是这样一个全局作用域的变量。
子树作用域
大多数时候,全局范围有点像大锤,我们需要一些更精确的东西。子树作用域中的变量作用域是应用程序的特定部分,而不是整个应用程序。
此级别的作用域可能是最少使用的,但是在确实需要使用时非常方便。 通常,一组组件需要共享很多相同的数据,并且通过props传递数据非常繁琐。
此作用域最适合用于共享上下文信息,这些上下文信息可以根据组件在应用程序中的位置进行更改,可以是这样的:
本地状态和数据-如果只有一小部分应用程序需要使用 Vuex,则无需使用 Vuex。 如果使用props传递会变得繁琐且麻烦,此时,子树作用域可能是我们最好的选择。
-
配置-有时我们需要组件以某种特定方式运行,但仅在应用程序的一部分中运行。 例如,注册表单中的所有
Input组件都需要验证,但是我们不想在整个应用程序中都要求验证。
使用子树作用域
子树作用域是通过使用provide和inject创建的。 我们提供希望可用于整个子树的值,然后将它们注入需要它们的组件中。
组件作用域
更具体一点,组件作用域使变量可用于单个组件。但是这不应该与更具体的实例作用域相混淆。
如果一个变量具有组件作用域,那么它就是一个组件的所有实例都可以使用的单个变量。我们可以拥有几个相同的组件,并且它们都能够访问相同的变量。
你可能熟悉 JS 中的模块作用域。在单个模块或文件中定义的任何内容都属于相同的模块作用域。由于组件是在单个文件中定义的,所以组件中的所有内容都在相同的模块作用域内。
使用组件作用域
要使用组件作用域,我们需要在与组件相同的文件中定义一个变量:
{{ componentScope }}<script>const componentScope = 'This is in the component scope'; export default { data() { return { componentScope: componentScope, }; }, };</script>" title="" data-original-title="复制">
<template>
<div class="new-component">
{{ componentScope }}
</div>
</template>
<script>
const componentScope = 'This is in the component scope';
export default {
data() {
return {
componentScope: componentScope,
};
},
};
</script>在此组件中渲染的变量componentScope是相同的变量,不管使用此组件多少次,componentScope 始终只有一个,没有多个副本。
如果此组件的一个实例修改了componentScope的值,则该组件的每个其他实例都会更改。 不应使用这种方式在组件之间进行通信,但这是共享数据的一种好方法。
实例作用域
实例作用域是我们可以获得的Vue作用域变量最常见形式,具有实例作用域的任何变量仅可用于组件的特定用法。 我们通常将其称为内部状态,有时也称为局部状态。
使用实例作用域
无论何时使用data()函数或使用computed props,都是在使用实例作用域。
甚至直接向组件实例添加属性也可以达到以下效果:
someMethod() {
this.newProperty = 'Instance scope';
}但是,如果以这种方式添加属性,则必须记住,它们不是响应式的。
英文原文地址:https://frontendsociety.com/why-you-shouldnt-use-vue-component-ff019fbcac2e?gi=ce7b162d53d4
为了保证的可读性,本文采用意译而非直译。
相关推荐:
更多编程相关知识,请访问:编程教学!!
The above is the detailed content of Detailed explanation of the 4 levels of scope in vue.js. For more information, please follow other related articles on the PHP Chinese website!
Netflix's Frontend: Examples and Applications of React (or Vue)Apr 16, 2025 am 12:08 AMNetflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.
The Frontend Landscape: How Netflix Approached its ChoicesApr 15, 2025 am 12:13 AMNetflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.
React vs. Vue: Which Framework Does Netflix Use?Apr 14, 2025 am 12:19 AMNetflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema
The Choice of Frameworks: What Drives Netflix's Decisions?Apr 13, 2025 am 12:05 AMNetflix mainly considers performance, scalability, development efficiency, ecosystem, technical debt and maintenance costs in framework selection. 1. Performance and scalability: Java and SpringBoot are selected to efficiently process massive data and high concurrent requests. 2. Development efficiency and ecosystem: Use React to improve front-end development efficiency and utilize its rich ecosystem. 3. Technical debt and maintenance costs: Choose Node.js to build microservices to reduce maintenance costs and technical debt.
React, Vue, and the Future of Netflix's FrontendApr 12, 2025 am 12:12 AMNetflix mainly uses React as the front-end framework, supplemented by Vue for specific functions. 1) React's componentization and virtual DOM improve the performance and development efficiency of Netflix applications. 2) Vue is used in Netflix's internal tools and small projects, and its flexibility and ease of use are key.
Vue.js in the Frontend: Real-World Applications and ExamplesApr 11, 2025 am 12:12 AMVue.js is a progressive JavaScript framework suitable for building complex user interfaces. 1) Its core concepts include responsive data, componentization and virtual DOM. 2) In practical applications, it can be demonstrated by building Todo applications and integrating VueRouter. 3) When debugging, it is recommended to use VueDevtools and console.log. 4) Performance optimization can be achieved through v-if/v-show, list rendering optimization, asynchronous loading of components, etc.
Vue.js and React: Understanding the Key DifferencesApr 10, 2025 am 09:26 AMVue.js is suitable for small to medium-sized projects, while React is more suitable for large and complex applications. 1. Vue.js' responsive system automatically updates the DOM through dependency tracking, making it easy to manage data changes. 2.React adopts a one-way data flow, and data flows from the parent component to the child component, providing a clear data flow and an easy-to-debug structure.
Vue.js vs. React: Project-Specific ConsiderationsApr 09, 2025 am 12:01 AMVue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.







