Home >Web Front-end >Vue.js >How to communicate in different situations in vue? way to share

How to communicate in different situations in vue? way to share

青灯夜游
青灯夜游forward
2022-04-20 20:39:142512browse

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!

How to communicate in different situations in vue? way to share

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 and inject 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: &#39;parent&#39;,
    // provide有两种写法
    // 第一种
    provide: {
        a: 1,
        b: 2
    }
    // 第二种
    provide() {
        return {
            a: 1,
            b: 2
        }
    }
}
</script>
// child.vue
// 此处忽略template模板的东西
<script>
export default {
    name: &#39;child&#39;,
    // inject
    // 第一种
    inject: [ &#39;a&#39;, &#39;b&#39; ]
    // 第二种
    inject: {
        abc: { // 可以指定任意不与data,props冲突的变量名,然后指定是指向provide中的哪个变量
            from: &#39;a&#39;,
            default: &#39;sfd&#39; // 如果默认值不是基本数据类型,那就得改用:default: () => {a:1,b:2}
        },
        b: {
            default: &#39;33&#39;
        }
    }
}
</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 &#39;vue&#39;
const EventBus = new Vue()
export default EventBus
// main.js
// 进行全局挂载
import eventBus from &#39;@/utils/eventBus&#39;
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(&#39;testBus&#39;, &#39;test&#39;)
        }
    }
}
// views/child.vue
<template>
    <div>
        {{ testContent }} <!-- test -->
    </div>
</template>
<script>
export default {
    data() {
        return {
            testContent: &#39;&#39;
        }
    },
    mounted() {
        this.$eventBus.$on(&#39;test&#39;, 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 ##class and style, the outermost tags class and style will be merged.
      • If the child component does not want to inherit the non-
      • prop attributes passed in by the parent component, you can use inheritAttrs to disable inheritance, and then pass v-bind="$ attrs" sets the externally passed non-prop attributes to the desired tag, but this will not change the class and 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
    • $attrs in the child component. The proxy gets all the values ​​passed by the parent component.
    • Example: This is the parent component

How to communicate in different situations in vue? way to share

    • # #This is a subcomponent: no props declared

    How to communicate in different situations in vue? way to share

    This is the dom display:

    • 此时,通过dom可以发现,所有没有声明的信息,全部出现在了子组件的根元素上。
    • 如果要让没有声明的信息不出现在子组件的根元素上,那就在子组件与data同级的位置加个属性:inheritAttrs: false;这样就不会未通过props接收的变量就不会出现在子组件的根元素上了
    • 至于怎么传递给子组件的子组件的子组件的子组件....等,那就需要给子组件的子组件依次都绑定:v-bind="$attrs"即可。
    • 注意这样只适用于传递数据。
  • $listeners
    • 官方解释:包含了父作用域中的 (不含 .native 修饰器的) v-on 事件监听器。它可以通过 v-on="$listeners" 传入内部组件——在创建更高层次的组件时非常有用
    • 当父组件向子组件传递回调时,子组件可以通过$listeners代理所有回调。
    • 示例:这是父组件

How to communicate in different situations in vue? way to share

    • 这是子组件

How to communicate in different situations in vue? way to share

    • 这是执行展示:

      How to communicate in different situations in vue? way to share

    • 同时可以发现子组件加上inheritAttrs:false之后根组件里的未声明props接受的变量消失了

      How to communicate in different situations in vue? way to share

  • 最后:建议最好不要用这个玩意,虽然他们都可以相对便捷的将第一级组件的属性,方法回调传递给N级子组件中的任一级,但是之后进行bug定位,或者分析需求将会是一个比较大的挑战。

不同窗口(同浏览器不同页签内)

同浏览器的不同页签之间的通讯,大多数的场景是:项目里的增删改查都是打开的新页面,然后新增结束后就触发列表页重新获取列表。这种场景下有什么方法呢?

监听stroage事件

// 需要监听的页面
mounted() {
    window.addEventListener(&#39;storage&#39;, this.storageEvent);
},
beforeDestroy() {
    window.removeEventListener()
}
methods: {
    storageEvent(e) {
        console.log("storage值发生变化后触发:", e)
    }
}
  • 切记:第一条:要记得将监听的事件在组件销毁之前解除监听。否则会给你惊”喜“
  • 切记:第二条:其中监听方法回调一定要在methods中定义,然后通过this进行引用,否则你在解除事件监听的时候将无效。

不同浏览器

不同浏览器的同一网站的有通讯的必要吗?
如果有那就:websocket(比如聊天室)
哈哈哈哈

(学习视频分享:web前端开发编程入门

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!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete