How to communicate in different situations in vue? The following article will analyze the communication methods in different situations in vue. I hope it will be helpful to everyone!
In fact, everyone is familiar with component communication in vue. Even if you open your mouth, after all, this is what is often asked in interviews. Since I had not considered it carefully before, when I was writing a small project, I encountered the need for communication in components, and then I started writing it. It turned out that it was useless. After checking for a long time, I realized that that method was not suitable for this situation. So after this incident, I decided to write an article to classify communication methods more clearly and carefully. After all, not every communication method is suitable for all scenarios. (Learning video sharing: vuejs tutorial)
Same window (that is, the same tab in the same browser)
Same What is mainly involved in the same page tab of the browser is the value transfer between parent and child components.
vuex: State Manager: Applicable to any component in a project, extremely inclusive
You probably don’t know the concept of a state manager. strangeness.
- Multiple components can share one or more status values. No matter how deep the component hierarchy is, it can be accessed normally. So this is an officially directly supported communication method.
- Note: For small single-page applications, this option is not very recommended. For small projects, using vuex will become more cumbersome, like a 75kg 150cm The clothes worn by a 170cm and 110kg person look very baggy and cannot be held up.
provide / inject (written based on v2.2.1 and above): suitable for N-level components, but must be the type of single-line inheritance
This pair Options need to be used together to allow an ancestor component to inject a dependency into all its descendants, no matter how deep the component hierarchy is, and for as long as the upstream and downstream relationships are established.
- It is equivalent to a building with N floors. The top level is the parent component. There is a common pipe between each floor. This pipe is provide. The pipe has an exit on each floor called: inject
- Note:
provide
andinject
bindings are not responsive. However, if you pass in a listenable object, the object's properties are still responsive. - Let’s take a look at the code
// parent.vue // 此处忽略template模板的东西 <script> export default { name: 'parent', // provide有两种写法 // 第一种 provide: { a: 1, b: 2 } // 第二种 provide() { return { a: 1, b: 2 } } } </script>
// child.vue // 此处忽略template模板的东西 <script> export default { name: 'child', // inject // 第一种 inject: [ 'a', 'b' ] // 第二种 inject: { abc: { // 可以指定任意不与data,props冲突的变量名,然后指定是指向provide中的哪个变量 from: 'a', default: 'sfd' // 如果默认值不是基本数据类型,那就得改用:default: () => {a:1,b:2} }, b: { default: '33' } } } </script>
props: applies to the value passed by two adjacent components (parent->child); $emit: child-> Parent
Serious props/$emit are too common, and they are all overused, so there is no need to write sample code.
- Only applicable to value transfer between parent and child components at adjacent levels
- Although props can also be used to transfer values for multi-level components, but this will make the code Very difficult to maintain and highly not recommended.
eventBus: The status is similar to that of vuex. It is suitable for any component and is extremely inclusive.
Problem:
- It is not convenient to maintain. : If used too much in a project, method name conflicts may cause exceptions, and it is more inconvenient to troubleshoot.
- Example:
// utils/eventBus.js import Vue from 'vue' const EventBus = new Vue() export default EventBus
// main.js // 进行全局挂载 import eventBus from '@/utils/eventBus' Vue.prototype.$eventBos = eventBus
// views/parent.vue <template> <div> <button @click="test">测试</button> </div> </template> <script> export default { data() { return {} }, methods: { test() { this.$eventBus.$emit('testBus', 'test') } } }
// views/child.vue <template> <div> {{ testContent }} <!-- test --> </div> </template> <script> export default { data() { return { testContent: '' } }, mounted() { this.$eventBus.$on('test', e => this.testContent = e) } }
$attrs / $listeners
- $attrs
-
Official Explanation :
- The properties passed from the parent component to the custom subcomponent, if there is no
prop
will be automatically set to the outermost label inside the subcomponent, if it is # For ##classand
style, the outermost tags
classand
stylewill be merged.
If the child component does not want to inherit the non- - prop
attributes passed in by the parent component, you can use
inheritAttrsto disable inheritance, and then pass
v-bind="$ attrs"sets the externally passed non-
propattributes to the desired tag, but this will not change the
classand
style
When the parent component passes values to the child component, but the child component does not declare all the passed values in props, you can use - The properties passed from the parent component to the custom subcomponent, if there is no
- $attrs
in the child component. The proxy gets all the values passed by the parent component.
Example: This is the parent component
-
Official Explanation :
-
- # #This is a subcomponent: no props declared
This is the dom display:- 此时,通过dom可以发现,所有没有声明的信息,全部出现在了子组件的根元素上。
- 如果要让没有声明的信息不出现在子组件的根元素上,那就在子组件与data同级的位置加个属性:inheritAttrs: false;这样就不会未通过props接收的变量就不会出现在子组件的根元素上了
- 至于怎么传递给子组件的子组件的子组件的子组件....等,那就需要给子组件的子组件依次都绑定:v-bind="$attrs"即可。
- 注意这样只适用于传递数据。
- $listeners
-
官方解释:包含了父作用域中的 (不含
.native
修饰器的)v-on
事件监听器。它可以通过v-on="$listeners"
传入内部组件——在创建更高层次的组件时非常有用 - 当父组件向子组件传递回调时,子组件可以通过$listeners代理所有回调。
示例:这是父组件
-
官方解释:包含了父作用域中的 (不含
这是子组件
-
这是执行展示:
-
同时可以发现子组件加上inheritAttrs:false之后根组件里的未声明props接受的变量消失了
- 最后:建议最好不要用这个玩意,虽然他们都可以相对便捷的将第一级组件的属性,方法回调传递给N级子组件中的任一级,但是之后进行bug定位,或者分析需求将会是一个比较大的挑战。
不同窗口(同浏览器不同页签内)
同浏览器的不同页签之间的通讯,大多数的场景是:项目里的增删改查都是打开的新页面,然后新增结束后就触发列表页重新获取列表。这种场景下有什么方法呢?
监听stroage事件
// 需要监听的页面 mounted() { window.addEventListener('storage', this.storageEvent); }, beforeDestroy() { window.removeEventListener() } methods: { storageEvent(e) { console.log("storage值发生变化后触发:", e) } }
- 切记:第一条:要记得将监听的事件在组件销毁之前解除监听。否则会给你惊”喜“
- 切记:第二条:其中监听方法回调一定要在methods中定义,然后通过this进行引用,否则你在解除事件监听的时候将无效。
不同浏览器
不同浏览器的同一网站的有通讯的必要吗?
如果有那就:websocket(比如聊天室)
哈哈哈哈
The above is the detailed content of How to communicate in different situations in vue? way to share. For more information, please follow other related articles on the PHP Chinese website!

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

Netflix 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.

Netflix 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 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 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 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.

The methods to implement the jump of a tag in Vue include: using the a tag in the HTML template to specify the href attribute. Use the router-link component of Vue routing. Use this.$router.push() method in JavaScript. Parameters can be passed through the query parameter and routes are configured in the router options for dynamic jumps.

There are the following methods to implement component jump in Vue: use router-link and <router-view> components to perform hyperlink jump, and specify the :to attribute as the target path. Use the <router-view> component directly to display the currently routed rendered components. Use the router.push() and router.replace() methods for programmatic navigation. The former saves history and the latter replaces the current route without leaving records.


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

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

Dreamweaver CS6
Visual web development tools