When writing a VUE project, data communication between components is essential. It’s a very important step. Today write several vUE components in the way of data communication and application scenarios.
props&@
-
props
The parent component uploads data to the child component parameters using the v-bind directive. The subcomponent is retrieved from the props property. Props can be received as arrays and objects. The following
-
An array
/ / the parent component <Children v-bind:msg="msg"></Children> // Defined on child components props: ["msg"] // The string corresponds to the v-bind value of the parent component's binding. Copy the code
-
Objects form
// parent <Children v-bind: MSG =" MSG "></Children> "Default data ", // default value require: true, // whether the item must be passed in},},Copy the code
A child component can only use properties that cannot be modified directly. Direct modification succeeds and vUE throws a warning, so this is not recommended.
-
-
@
The parent component passes a method to the child component. Child components can call this method to modify the value of the parent component (resolved that the child cannot modify the value of the parent component).
// Pass the defined FN in the parent component for the child component to call. <Children @fn="fn"></Children> // The child component calls fn via $emit. this.$emit("fn".1.2.3); Copy the code
ref
Add the REF attribute to the child registered by the parent. The parent component can get an instance of the child component using the this.$refs. property name. I can do it directly.
<Children ref="subInst" /> this.$refs.subInstCopy the code
provide&inject
Provide data in the parent component and inject data in the child component. Provide the option should be: an object or function that returns an object Inject the option should be: an array of strings, or an object whose key is the local binding name
// Add the method provide() {return {MSG: this.msg, // add the method provide() {return {MSG: this.msg, // You need to pass a responsive object. }, // Inject: [" MSG "],Copy the code
Provide and Inject are mainly used to provide use cases for high-level plug-ins/component libraries and are not recommended for direct use in application code.
attrs&listeners
These two properties are one object. Save the data and methods passed down from the parent component, respectively.
-
$attrs
<template> <div class="hello"> <div class="hello"> I'm attrs -- {{ $attrs. MSG}} // The value on $attrs is read-only and not responsive. Forcing $set to set vUE throws a warning. This is a read-only attribute. </div> </template>Copy the code
-
$listeners
<template> <div class="hello"> </div> </template> </ function ></ function ></ function ></ function > this.$listeners.fn(); Echo this.$emit("fn"); }Copy the code
sync&model
This is the syntactic sugar that comes with the VUE component. Easy to call.
-
sync
$emit("update: MSG ", "789"); // Parent <Children :msg.sync=" MSG "></Children> // Call this method directly on the child component, passing the value to change the value.Copy the code
The.sync modifier is equivalent to vue internally defining methods that can change values, and is equivalent to passing functions on parent components using @. Print an instance of the child component, and you’ll see the update: MSG method appear on Listen.
-
model
$emit("input", <Children v-model=" MSG "></Children> </Children> </Children> value); // By default, the v-model of input <input type="text" v-model="value" /> // the child component directly modifs the value of the premise props.Copy the code
The V-model is used for bidirectional binding of form data, which does two things:
2. The V-on directive binds the input event to the current element
The default value and event values can be modified by model in the child component. case
model: { prop: "check", event: "change", }, Copy the code
Note that invoking the V-model on the component still requires you to bind the value and modify the value operation.
eventBus
By creating a new vUE instance, use it as an event car and then hook it onto the vUE prototype. You can communicate by publishing and subscribing. This method can be used between any component, but is passed down from the parent component.
Prototype.$eventBus = new Vue(); This.$eventBus.$on("callback", (data) => {console.log(" received data----", data); }); This.$eventBus.$emit("callback", "callback");Copy the code
You can use this method to communicate between any two components. Extremely convenient. The downside is that projects are complex and sometimes difficult to maintain and track.
parent&children
The $emit method is recursively executed by mounting the prototype on Vue. Subscribe to publications on components that need to be communicated.
-
parent
Vue.prototype.$dispatch = function (eventName, params) { var parent = this.$parent; while (parent) { parent.$emit(eventName, params); parent = parent.$parent; }} // Define a method on the prototype that internally executes the $emit method all the way up the chain.Copy the code
$on("Up", function (params) {this. MSG = params; }); This.$dispatch("Up", "I changed data by parent ");Copy the code
-
children
Prototype.$notice = function (eventName, params) {var children = this.$children; function deep(children) { children.forEach(item => { item.$emit(eventName, params); if (item.children) { deep(children); }}); } deep(children); } // Define a method on the prototype that internally recursively calls the subordinate $emit method.Copy the code
$on("down", function (params) {this. MSG = params; }); $notice("down", "I changed data by children "); $notice("down"," I changed data by children ");Copy the code
These two notations are commonly used in packaged components. The advantage is that you can go all the way up or down. The downside is contamination of the Vue prototype.
slot
This writing uses the child’s data in the parent component. Also known as scope slot (other uses of slot are not mentioned).
</ / Parent <children> <template V-slot :header="scope"> <h1>{{scope.header}}</h1 <slot name="header" :header="123"></slot>Copy the code
For example, Element’s table editable content is implemented by the scope slot. Interested can look at the source code.
vuex
Vuex is a state management mode developed specifically for vue.js applications
Vuex is arguably the best data manager of the bunch. The most important is reactive (vUE based), where data is shared between components.
I’ll skip the API here. After all, this thing uses vUE’s basic to use this thing. Everyone is familiar.
-
state
The property of the stored data cannot be directly modified by the property value of state.
-
mutations
The synchronized method to change state is triggered by commit
const store = new Vuex.Store({ state: { count: 1 }, mutations: {increment (state,a) {increment (state,a) {increment (state,a) {increment (state,a) {increment (state,a) {increment (state,a) {increment (state,a) {increment (state,a) {increment (state,a)}}})Copy the code
-
actions
-
The Action commits mutation rather than a direct state change.
-
Actions can contain any asynchronous operation.
const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment (state) { state.count++ } }, actions: {increment (context) {context.com MIT ('increment')}}}) // Trigger store.dispatch("increment"); // The asynchronous operation is required to return a promise.Copy the code
-
-
getters
Equivalent to computed properties in VUE.
const store = new Vuex.Store({ state: { todos: [ { id: 1, text: '...', done: true }, { id: 2, text: '...', done: false } ] }, getters: { doneTodos: State => {return state.todos.filter(todo => todo.done)}}}) // Access store.getters.donetodosCopy the code
-
Modules (abbreviated)
-
Auxiliary function
- mapState
- mapActions
- mapMutations
-
mapGetters
The function is returned as an array of the corresponding property names defined in vuex. Returns an object.
conclusion
The above is my summary of VUE data communication. If you find this article useful, you are welcome to give a “like”, also welcome technical discussion, thank you!