How to communicate in different situations in vue? way to share
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!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

There are three ways to refer to JS files in Vue.js: directly specify the path using the <script> tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses <router-link to="/" component window.history.back(), and the method selection depends on the scene.

You can query the Vue version by using Vue Devtools to view the Vue tab in the browser's console. Use npm to run the "npm list -g vue" command. Find the Vue item in the "dependencies" object of the package.json file. For Vue CLI projects, run the "vue --version" command. Check the version information in the <script> tag in the HTML file that refers to the Vue file.

Function interception in Vue is a technique used to limit the number of times a function is called within a specified time period and prevent performance problems. The implementation method is: import the lodash library: import { debounce } from 'lodash'; Use the debounce function to create an intercept function: const debouncedFunction = debounce(() => { / Logical / }, 500); Call the intercept function, and the control function is called at most once in 500 milliseconds.
