国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Method 1, props/$emit
1. Parent component passes value to child component
2. Child components pass values ??to parent components (through events)
Method 2, $emit/$on
Method 3, vuex
attrs/attrs/listeners" >方法四、attrs/attrs/listeners
方法五、provide/inject
parent/parent /children與 ref" >方法六、parent/parent /children與 ref
Home Web Front-end Vue.js How to communicate between Vue components? Brief analysis of six methods

How to communicate between Vue components? Brief analysis of six methods

Mar 22, 2023 pm 04:54 PM
front end vue.js Component communication

How to communicate between Vue components? The following article will introduce you to the six ways of Vue component communication. I hope it will be helpful to you!

How to communicate between Vue components? Brief analysis of six methods

Components are one of the most powerful features of vue.js, and the scopes of component instances are independent of each other, which means that data between different components cannot Cross-referencing. Generally speaking, components can have several relationships.

How to choose an effective communication method for different usage scenarios? This is the topic we are going to explore. This article summarizes several ways of communication between Vue components, such as props, emit/emit/on, vuex, parent/parent/children, attrs/attrs/listeners and provide/inject, and explains the differences with easy-to-understand examples. and usage scenarios, I hope it can be of some help to my friends. [Related recommendations: vuejs video tutorial, web front-end development]

Method 1, props/$emit

The way parent component A passes props Passing to sub-component B, B to A is achieved by $emit in component B and v-on in component A.

1. Parent component passes value to child component

Next we use an example to illustrate how the parent component passes value to child component: in the child component Users.vue How to get the data in the parent component App.vue users:["Henry","Bucky","Emily"]

//App.vue父組件
<template>
  <div id="app">
    <users v-bind:users="users"></users>//前者自定義名稱便于子組件調(diào)用,后者要傳遞數(shù)據(jù)名
  </div>
</template>
<script>
import Users from "./components/Users"
export default {
  name: &#39;App&#39;,
  data(){
    return{
      users:["Henry","Bucky","Emily"]
    }
  },
  components:{
    "users":Users
  }
}
//users子組件
<template>
  <div class="hello">
    <ul>
      <li v-for="user in users">{{user}}</li>//遍歷傳遞過(guò)來(lái)的值,然后呈現(xiàn)到頁(yè)面
    </ul>
  </div>
</template>
<script>
export default {
  name: &#39;HelloWorld&#39;,
  props:{
    users:{           //這個(gè)就是父組件中子標(biāo)簽自定義名字
      type:Array,
      required:true
    }
  }
}
</script>

Summary: The parent component passes data downward to the child component through props. Note: There are three forms of data in the component: data, props, computed

2. Child components pass values ??to parent components (through events)

Next, we use an example to illustrate how the sub-component passes a value to the parent component: when we click "Vue.js Demo", the sub-component passes a value to the parent component, and the text changes from the original "A value is passed" to "Child passes value to parent component" to realize the transfer of value from child component to parent component.

// 子組件
<template>
  <header>
    <h1 @click="changeTitle">{{title}}</h1>//綁定一個(gè)點(diǎn)擊事件
  </header>
</template>
<script>
export default {
  name: &#39;app-header&#39;,
  data() {
    return {
      title:"Vue.js Demo"
    }
  },
  methods:{
    changeTitle() {
      this.$emit("titleChanged","子向父組件傳值");//自定義事件  傳遞值“子向父組件傳值”
    }
  }
}
</script>
// 父組件
<template>
  <div id="app">
    <app-header v-on:titleChanged="updateTitle" ></app-header>//與子組件titleChanged自定義事件保持一致
   // updateTitle($event)接受傳遞過(guò)來(lái)的文字
    <h2>{{title}}</h2>
  </div>
</template>
<script>
import Header from "./components/Header"
export default {
  name: &#39;App&#39;,
  data(){
    return{
      title:"傳遞的是一個(gè)值"
    }
  },
  methods:{
    updateTitle(e){   //聲明這個(gè)函數(shù)
      this.title = e;
    }
  },
  components:{
   "app-header":Header,
  }
}
</script>

Summary: The child component sends messages to the parent component through events. In fact, the child component sends its own data to the parent component.

Method 2, $emit/$on

This method passes an empty The Vue instance serves as the central event bus (event center), using it to trigger events and listen for events, cleverly and lightweightly realizing communication between any components, including parent-child, brother, and cross-level . When our project is relatively large, we can choose vuex, a better state management solution.

1. Specific implementation method:

    var Event=new Vue();
    Event.$emit(事件名,數(shù)據(jù));
    Event.$on(事件名,data => {});

2. For example

Assume that there are three sibling components, namely A, B, and C components. How does C component obtain A? Or the data of component B

<div id="itany">
	<my-a></my-a>
	<my-b></my-b>
	<my-c></my-c>
</div>
<template id="a">
  <div>
    <h3>A組件:{{name}}</h3>
    <button @click="send">將數(shù)據(jù)發(fā)送給C組件</button>
  </div>
</template>
<template id="b">
  <div>
    <h3>B組件:{{age}}</h3>
    <button @click="send">將數(shù)組發(fā)送給C組件</button>
  </div>
</template>
<template id="c">
  <div>
    <h3>C組件:{{name}},{{age}}</h3>
  </div>
</template>
<script>
var Event = new Vue();//定義一個(gè)空的Vue實(shí)例
var A = {
	template: &#39;#a&#39;,
	data() {
	  return {
	    name: &#39;tom&#39;
	  }
	},
	methods: {
	  send() {
	    Event.$emit(&#39;data-a&#39;, this.name);
	  }
	}
}
var B = {
	template: &#39;#b&#39;,
	data() {
	  return {
	    age: 20
	  }
	},
	methods: {
	  send() {
	    Event.$emit(&#39;data-b&#39;, this.age);
	  }
	}
}
var C = {
	template: &#39;#c&#39;,
	data() {
	  return {
	    name: &#39;&#39;,
	    age: ""
	  }
	},
	mounted() {//在模板編譯完成后執(zhí)行
	Event.$on(&#39;data-a&#39;,name => {
	     this.name = name;//箭頭函數(shù)內(nèi)部不會(huì)產(chǎn)生新的this,這邊如果不用=>,this指代Event
	})
	Event.$on(&#39;data-b&#39;,age => {
	     this.age = age;
	})
	}
}
var vm = new Vue({
	el: &#39;#itany&#39;,
	components: {
	  &#39;my-a&#39;: A,
	  &#39;my-b&#39;: B,
	  &#39;my-c&#39;: C
	}
});	
</script>

$on listens to the custom events data-a and data-b, because sometimes it is not sure when the event will be triggered, usually in the mounted or created hook Come in to monitor.

Method 3, vuex

How to communicate between Vue components? Brief analysis of six methods

1. Briefly introduce the principle of Vuex Vuex implements a one-way data flow and has a State to store data globally. When a component wants to change the data in the State, it must be done through Mutation. Mutation also provides a subscriber mode for external plug-ins to call to obtain updates to the State data. When all asynchronous operations (commonly called back-end interfaces are used to obtain update data asynchronously) or batch synchronous operations require Action, Action cannot directly modify State. State data still needs to be modified through Mutation. Finally, based on the changes in State, it is rendered to the view.

2.簡(jiǎn)要介紹各模塊在流程中的功能: Vue Components:Vue組件。HTML頁(yè)面上,負(fù)責(zé)接收用戶操作等交互行為,執(zhí)行dispatch方法觸發(fā)對(duì)應(yīng)action進(jìn)行回應(yīng)。 dispatch:操作行為觸發(fā)方法,是唯一能執(zhí)行action的方法。 actions:操作行為處理模塊,由組件中的$store.dispatch('action 名稱', data1)來(lái)觸發(fā)。然后由commit()來(lái)觸發(fā)mutation的調(diào)用 , 間接更新 state。負(fù)責(zé)處理Vue Components接收到的所有交互行為。包含同步/異步操作,支持多個(gè)同名方法,按照注冊(cè)的順序依次觸發(fā)。向后臺(tái)API請(qǐng)求的操作就在這個(gè)模塊中進(jìn)行,包括觸發(fā)其他action以及提交mutation的操作。該模塊提供了Promise的封裝,以支持action的鏈?zhǔn)接|發(fā)。 commit:狀態(tài)改變提交操作方法。對(duì)mutation進(jìn)行提交,是唯一能執(zhí)行mutation的方法。 mutations:狀態(tài)改變操作方法,由actions中的commit('mutation 名稱')來(lái)觸發(fā)。是Vuex修改state的唯一推薦方法。該方法只能進(jìn)行同步操作,且方法名只能全局唯一。操作之中會(huì)有一些hook暴露出來(lái),以進(jìn)行state的監(jiān)控等。 state:頁(yè)面狀態(tài)管理容器對(duì)象。集中存儲(chǔ)Vue components中data對(duì)象的零散數(shù)據(jù),全局唯一,以進(jìn)行統(tǒng)一的狀態(tài)管理。頁(yè)面顯示所需的數(shù)據(jù)從該對(duì)象中進(jìn)行讀取,利用Vue的細(xì)粒度數(shù)據(jù)響應(yīng)機(jī)制來(lái)進(jìn)行高效的狀態(tài)更新。 getters:state對(duì)象讀取方法。圖中沒(méi)有單獨(dú)列出該模塊,應(yīng)該被包含在了render中,Vue Components通過(guò)該方法讀取全局state對(duì)象。 3.Vuex與localStorage vuex 是 vue 的狀態(tài)管理器,存儲(chǔ)的數(shù)據(jù)是響應(yīng)式的。但是并不會(huì)保存起來(lái),刷新之后就回到了初始狀態(tài),具體做法應(yīng)該在vuex里數(shù)據(jù)改變的時(shí)候把數(shù)據(jù)拷貝一份保存到localStorage里面,刷新之后,如果localStorage里有保存的數(shù)據(jù),取出來(lái)再替換store里的state。

let defaultCity = "上海"
try {   // 用戶關(guān)閉了本地存儲(chǔ)功能,此時(shí)在外層加個(gè)try...catch
  if (!defaultCity){
    defaultCity = JSON.parse(window.localStorage.getItem(&#39;defaultCity&#39;))
  }
}catch(e){}
export default new Vuex.Store({
  state: {
    city: defaultCity
  },
  mutations: {
    changeCity(state, city) {
      state.city = city
      try {
      window.localStorage.setItem(&#39;defaultCity&#39;, JSON.stringify(state.city));
      // 數(shù)據(jù)改變的時(shí)候把數(shù)據(jù)拷貝一份保存到localStorage里面
      } catch (e) {}
    }
  }
})

這里需要注意的是:由于vuex里,我們保存的狀態(tài),都是數(shù)組,而localStorage只支持字符串,所以需要用JSON轉(zhuǎn)換:

JSON.stringify(state.subscribeList);   // array -> string
JSON.parse(window.localStorage.getItem("subscribeList"));    // string -> array 
復(fù)制代碼

方法四、attrs/attrs/listeners

1.簡(jiǎn)介

多級(jí)組件嵌套需要傳遞數(shù)據(jù)時(shí),通常使用的方法是通過(guò)vuex。但如果僅僅是傳遞數(shù)據(jù),而不做中間處理,使用 vuex 處理,未免有點(diǎn)大材小用。為此Vue2.4 版本提供了另一種方法----attrs/attrs/listeners

##attrs: Contains items not included in the parent scope that are propIdentified ( and obtained the property binding of )(class and styleexcept ). When a component does not declare any prop, all parent scopes will be included here Binding (class and styleexcept ) , and can be passed v?bind ="attrs: Contains attribute bindings (except class and style) in the parent scope that are not recognized (and obtained) by prop. When a When the component does not declare any props, all parent scope bindings (except class and style) will be included here, and can be passed v-bind="

listeners:包含了父作用域中的(不含.native修飾器的)v?on事件監(jiān)聽(tīng)器。它可以通過(guò)v?on="listeners:包含了父作用域中的 (不含 .native 修飾器的) v-on 事件監(jiān)聽(tīng)器。它可以通過(guò) v-on="listeners" 傳入內(nèi)部組件

接下來(lái)我們看個(gè)跨級(jí)通信的例子:

// index.vue
<template>
  <div>
    <h2>浪里行舟</h2>
    <child-com1
      :foo="foo"
      :boo="boo"
      :coo="coo"
      :doo="doo"
      title="前端工匠"
    ></child-com1>
  </div>
</template>
<script>
const childCom1 = () => import("./childCom1.vue");
export default {
  components: { childCom1 },
  data() {
    return {
      foo: "Javascript",
      boo: "Html",
      coo: "CSS",
      doo: "Vue"
    };
  }
};
</script>
// childCom1.vue
<template class="border">
  <div>
    <p>foo: {{ foo }}</p>
    <p>childCom1的$attrs: {{ $attrs }}</p>
    <child-com2 v-bind="$attrs"></child-com2>
  </div>
</template>
<script>
const childCom2 = () => import("./childCom2.vue");
export default {
  components: {
    childCom2
  },
  inheritAttrs: false, // 可以關(guān)閉自動(dòng)掛載到組件根元素上的沒(méi)有在props聲明的屬性
  props: {
    foo: String // foo作為props屬性綁定
  },
  created() {
    console.log(this.$attrs); // { "boo": "Html", "coo": "CSS", "doo": "Vue", "title": "前端工匠" }
  }
};
</script>
// childCom2.vue
<template>
  <div class="border">
    <p>boo: {{ boo }}</p>
    <p>childCom2: {{ $attrs }}</p>
    <child-com3 v-bind="$attrs"></child-com3>
  </div>
</template>
<script>
const childCom3 = () => import("./childCom3.vue");
export default {
  components: {
    childCom3
  },
  inheritAttrs: false,
  props: {
    boo: String
  },
  created() {
    console.log(this.$attrs); // { "coo": "CSS", "doo": "Vue", "title": "前端工匠" }
  }
};
</script>
// childCom3.vue
<template>
  <div class="border">
    <p>childCom3: {{ $attrs }}</p>
  </div>
</template>
<script>
export default {
  props: {
    coo: String,
    title: String
  }
};
</script>

How to communicate between Vue components? Brief analysis of six methods

如上圖所示attrs表示沒(méi)有繼承數(shù)據(jù)的對(duì)象,格式為屬性名:屬性值。Vue2.4提供了attrs表示沒(méi)有繼承數(shù)據(jù)的對(duì)象,格式為{屬性名:屬性值}。Vue2.4提供了attrs , $listeners 來(lái)傳遞數(shù)據(jù)與事件,跨級(jí)組件之間的通訊變得更簡(jiǎn)單。

簡(jiǎn)單來(lái)說(shuō):attrsattrs與listeners 是兩個(gè)對(duì)象,attrs里存放的是父組件中綁定的非Props屬性,attrs 里存放的是父組件中綁定的非 Props 屬性,listeners里存放的是父組件中綁定的非原生事件。

方法五、provide/inject

1.簡(jiǎn)介

Vue2.2.0新增API,這對(duì)選項(xiàng)需要一起使用,以允許一個(gè)祖先組件向其所有子孫后代注入一個(gè)依賴,不論組件層次有多深,并在起上下游關(guān)系成立的時(shí)間里始終生效。一言而蔽之:祖先組件中通過(guò)provider來(lái)提供變量,然后在子孫組件中通過(guò)inject來(lái)注入變量。 provide / inject API 主要解決了跨級(jí)組件間的通信問(wèn)題,不過(guò)它的使用場(chǎng)景,主要是子組件獲取上級(jí)組件的狀態(tài),跨級(jí)組件間建立了一種主動(dòng)提供與依賴注入的關(guān)系。

2.舉個(gè)例子

假設(shè)有兩個(gè)組件: A.vue 和 B.vue,B 是 A 的子組件

// A.vue
export default {
  provide: {
    name: &#39;浪里行舟&#39;
  }
}
// B.vuee
xport default {
  inject: [&#39;name&#39;],  mounted () {
    console.log(this.name);  // 浪里行舟
  }
}

可以看到,在 A.vue 里,我們?cè)O(shè)置了一個(gè) provide: name,值為 浪里行舟,它的作用就是將 name 這個(gè)變量提供給它的所有子組件。而在 B.vue 中,通過(guò) inject 注入了從 A 組件中提供的 name 變量,那么在組件 B 中,就可以直接通過(guò) this.name 訪問(wèn)這個(gè)變量了,它的值也是 浪里行舟。這就是 provide / inject API 最核心的用法。

需要注意的是:provide 和 inject 綁定并不是可響應(yīng)的。這是刻意為之的。然而,如果你傳入了一個(gè)可監(jiān)聽(tīng)的對(duì)象,那么其對(duì)象的屬性還是可響應(yīng)的----vue官方文檔 所以,上面 A.vue 的 name 如果改變了,B.vue 的 this.name 是不會(huì)改變的,仍然是 浪里行舟。

方法六、parent/parent /children與 ref

ref:如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;如果用在子組件上,引用就指向組件實(shí)例parent/parent /children:訪問(wèn)父 / 子實(shí)例 需要注意的是:這兩種都是直接得到組件實(shí)例,使用后可以直接調(diào)用組件的方法或訪問(wèn)數(shù)據(jù)。我們先來(lái)看個(gè)用 ref來(lái)訪問(wèn)組件的例子

// component-a 子組件
export default {
  data () {
    return {
      title: &#39;Vue.js&#39;
    }
  },
  methods: {
    sayHello () {
      window.alert(&#39;Hello&#39;);
    }
  }
}
// 父組件
<template>
  <component-a ref="comA"></component-a>
</template>
<script>
  export default {
    mounted () {
      const comA = this.$refs.comA;
      console.log(comA.title);  // Vue.js
      comA.sayHello();  // 彈窗
    }
  }
</script>
復(fù)制代碼

不過(guò),這兩種方法的弊端是,無(wú)法在跨級(jí)或兄弟間通信。

(學(xué)習(xí)視頻分享:vuejs入門(mén)教程編程基礎(chǔ)視頻

The above is the detailed content of How to communicate between Vue components? Brief analysis of six methods. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Vue: a perfect pairing of front-end development tools PHP and Vue: a perfect pairing of front-end development tools Mar 16, 2024 pm 12:09 PM

PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

Exploring Go language front-end technology: a new vision for front-end development Exploring Go language front-end technology: a new vision for front-end development Mar 28, 2024 pm 01:06 PM

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

Is Django front-end or back-end? check it out! Is Django front-end or back-end? check it out! Jan 19, 2024 am 08:37 AM

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

Vue.js vs. React: Project-Specific Considerations Vue.js vs. React: Project-Specific Considerations Apr 09, 2025 am 12:01 AM

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.

C# development experience sharing: front-end and back-end collaborative development skills C# development experience sharing: front-end and back-end collaborative development skills Nov 23, 2023 am 10:13 AM

As a C# developer, our development work usually includes front-end and back-end development. As technology develops and the complexity of projects increases, the collaborative development of front-end and back-end has become more and more important and complex. This article will share some front-end and back-end collaborative development techniques to help C# developers complete development work more efficiently. After determining the interface specifications, collaborative development of the front-end and back-end is inseparable from the interaction of API interfaces. To ensure the smooth progress of front-end and back-end collaborative development, the most important thing is to define good interface specifications. Interface specification involves the name of the interface

Questions frequently asked by front-end interviewers Questions frequently asked by front-end interviewers Mar 19, 2024 pm 02:24 PM

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

Vue and Vue-Router: How to share data between components? Vue and Vue-Router: How to share data between components? Dec 17, 2023 am 09:17 AM

Vue and Vue-Router: How to share data between components? Introduction: Vue is a popular JavaScript framework for building user interfaces. Vue-Router is Vue's official routing manager, used to implement single-page applications. In Vue applications, components are the basic units for building user interfaces. In many cases we need to share data between different components. This article will introduce some methods to help you achieve data sharing in Vue and Vue-Router, and

Django: A magical framework that can handle both front-end and back-end development! Django: A magical framework that can handle both front-end and back-end development! Jan 19, 2024 am 08:52 AM

Django: A magical framework that can handle both front-end and back-end development! Django is an efficient and scalable web application framework. It is able to support multiple web development models, including MVC and MTV, and can easily develop high-quality web applications. Django not only supports back-end development, but can also quickly build front-end interfaces and achieve flexible view display through template language. Django combines front-end development and back-end development into a seamless integration, so developers don’t have to specialize in learning

See all articles