In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Editor to share with you what are the methods of transmitting data in vuejs, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
Transfer methods: 1, the parent component of the use of "props" to transfer data to child components; 2, child components use "this.$emit (" events ")" to transfer data to the parent component; 3, brother components use public files to transfer data; 4, parent and child components use "ref/refs" to transfer data; 5, use Vuex to transfer data, and so on.
The operating environment of this tutorial: windows7 system, vue2.9.6 version, DELL G3 computer.
one。 Father-to-son transmission
(1) bind an attribute to the child component tag of the parent component and mount the variable to be transferred
(2) accept data through props in sub-components. Props can be an array or an object. The accepted data can directly use props: ["attribute name"] props: {attribute name: data type}
Code example:
/ / parent component
Parent component
Import son from ". / son.vue"; / / Import parent component export default {components: {son}, / / register component name: "parent component", data () {return {name: "Frazier", / / parent component definition variable};},}; / / child component
{{data}}
Export default {components: {}, name: 'subcomponents', props: ["data"],}; two. Pass on from son to father
(1) customize an event on the child component label of the parent component, and then call the required method
(2) the event defined in the parent component is triggered by this.$emit ("event") in the method of the child component, and the data is passed in the form of parameters.
Code example:
/ / parent component
Parent component / / customize an event
Import son from ". / son.vue"; / / Import parent component export default {components: {son}, / / register component name: "parent component", data () {return {};}, methods: {lcclick () {alert ('child parent')}},}; / / child component
Click me.
Export default {components: {}, name: 'sub-component', methods: {lcalter () {this.$emit ('lcclick') / / trigger event} through emit},}; three. Brother component communication (bus bus)
(1) create a new Bus.js file in src, and then export an empty vue instance
(2) Bus.js is introduced into the data transmission side and then through Bus. Emit ("event name", "parameter") to dispatch events, data is to dispatch events as emit ("event name", "parameter"), data is to dispatch events as emit ("event name", "parameter"), and data is to be transmitted in the form of parameters of emit ()
(3) introduce Bus.js on the side of the accepted data and then pass Bus.$on ("event name", (data) = > {data is the accepted data})
Example of a picture:
IV. Ref/refs (parent-child component communication)
(1) if ref is used on ordinary DOM elements, the reference points to the DOM element; if used on subcomponents, the reference points to the component instance.
(2) you can call the method of the component or access the data directly through the instance. It is also a kind of child component passing values to the parent component.
Code example:
/ / parent component
SayHello
Import child from'. / child.vue' export default {components: {child}, data () {return {childForRef: null,}}, mounted () {this.childForRef = this.$refs.childForRef; console.log (this.childForRef.name);}, methods: {sayHello () {this.childForRef.sayHello ()}} / / subcomponents
The content of child
Export default {data () {return {name:'I am child',}}, methods: {sayHello () {console.log ('hello'); alert (' hello');}} V Vuex Communications
Components operate asynchronously through dispatch to actions,actions, and then change state through commit to mutations,mutations in actions, then change state through logical operations, so as to synchronize to the component and update its data state.
Code example:
/ / parent component template >
Import ChildA from'. / ChildA' / / Import component An import ChildB from'. / ChildB' / / Import component B export default {components: {ChildA, ChildB} / / Registration component} / / Sub-component An I am component A point I let component B receive data
Because of clicking B, the information has changed: {{BMessage}}
Export default {data () {return {AMessage: 'Hello,B component, I am component A'}}, computed: {BMessage () {/ / the data of component B obtained from store is stored here return this.$store.state.BMsg}}, methods: {transform () {/ / trigger receiveAMsg Store the data of component An in store, this.$store.commit ('receiveAMsg', {AMsg: this.AMessage})}} / / Sub-component B I am component B, and I let component A receive the data.
Click A, my information has changed: {{AMessage}}
Export default {data () {return {BMessage: 'Hello,A component, I am component B'}}, computed: {AMessage () {/ / the data of component An obtained from store is stored here return this.$store.state.AMsg}}, methods: {transform () {/ / trigger receiveBMsg Store the data of component B in store this.$store.commit ('receiveBMsg', {BMsg: this.BMessage})}} / / vueximport Vue from' vue' import Vuex from 'vuex' Vue.use (Vuex) const state = {AMsg:', BMsg:''} const mutations = {receiveAMsg (state) Payload) {/ / store the data of component An in state state.AMsg = payload.AMsg}, and receiveBMsg (state, payload) {/ / store the data of component B in state state.BMsg = payload.BMsg}} export default new Vuex.Store ({state, mutations}). $parent
The parent component instance can be obtained through parent, and then the properties and methods of the parent component can be accessed through this instance. It also has a sibling parent that can get the parent component instance, and then access the properties and methods of the parent component through this instance. It also has a sibling parent that can get the parent component instance, and then access the properties and methods of the parent component through this instance. It also has a sibling root. You can get the root component instance.
Code example:
/ / the data this.$parent.foo// of the parent component is written to the data of the parent component this.$parent.foo = 2max / access to the calculation property of the parent component this.$parent.bar// calls the method this.$parent.baz () of the parent component / / in the example of passing the child component to the parent component, you can use this.$parent.getNum (100) to pass the value to the parent component. 7. SessionStorage passing value
SessionStorage is the global object of the browser, and the data stored in it will be erased when the page is closed. With this feature, we can share a piece of data on all pages.
Code example:
/ / Save data to sessionStoragesessionStorage.setItem ('key',' value'); / / get data from sessionStorage let data = sessionStorage.getItem ('key'); / / delete saved data sessionStorage.removeItem (' key') from sessionStorage; / / delete all saved data sessionStorage.clear () from sessionStorage
Note: what is stored in it is a key-value pair, which can only be a string type. If you want to save an object, you need to use let objStr = JSON.stringify (obj) to convert it into a string and then store it (when used, let obj = JSON.parse (objStr) parses to an object).
Recommend a library, good-storage, which encapsulates sessionStorage and can store objects directly with its API.
/ / localStorage storage.set (key,val) storage.get (key, def) / / sessionStorage storage.session.set (key,val) storage.session.get (key,val) VIII. Routing value
Use question marks to pass values
Use this when page A jumps to page B. R o u t e r. P u s h ('/ B? N a m e = d a n s e e k') B page can be used to use t h i s. You can use this for the router.push ('/ Backnamekeeper danseek') B page. The router.push ('/ Backnamekeeper danseek') B page can use this.route.query.name to get the value passed from page A
Pay attention to the difference between router and route above
Use colons to pass values
Configure the following routes:
{path:'/ views/B.vue' component: () = > import ('.. / views/B.vue')}
On the B page, you can use this.$route.params.name to get the value of the routing incoming name.
Use parent-child components to pass values
Since router-view itself is also a component, we can also use parent-child components to pass values, and then add props to the corresponding child page. Because the route is not refreshed after the type update, we cannot directly get the latest type value in the mounted hook of the child page. Instead, we use watch.
/ / Sub-page props: ['type'] watch: {type () {/ / console.log ("you can always get the latest data in this method: type=", this.type)},}, nine. Grandparents and grandchildren $attrs
Normally, you need to use the father's props as an intermediate transition, but in this way, there will be more attributes in the parent component that have nothing to do with the business of the parent component, with a high degree of coupling, which can be simplified with the help of $attrs, and grandparents and grandchildren do not need to modify.
Ancestor components:
Import Parent from'. / Parent' export default {name: "GrandParent", components: {Parent}, data () {return {}}, methods: {sayKnow (val) {console.log (val)}}, mounted () {}}
Parent component
Parent component received
Grandfather's name: {{name}}
Import Children from'. / Children' export default {name: "Parent", components: {Children}, / / the parent component received the name, so the name value is not passed to the props of the child component: ['name'], data () {return {}, methods: {}, mounted () {}}
Sub-component
Subcomponents received.
Grandfather's name: {{name}}
Grandfather's gender: {{sex}}
Grandfather's age: {{age}}
Grandfather's hobby: {{hobby}}
I know that export default {name: "Children", components: {}, / / because the parent component has received the name attribute So name will not be passed to subcomponents props: ['sex','age','hobby','name'], data () {return {}}, methods: {sayKnow () {this.$emit (' sayKnow',' I know')}}, mounted () {}} ten. Sun Chuanzu uses $listeners
The content of the text is the same as the ninth
Ancestor component
{{msg}}
Import ChildrenOne from'.. / src/components/children.vue'export default {name: 'App', components: {ChildrenOne,}, data () {return {msg:'}}, methods: {eventOne (value) {this.msg = value}
Parent component
Import ChildrenTwo from'. / childrenTwo.vue'export default {name: 'childrenOne', components: {ChildrenTwo}}
Sub-component
Click to pass it to Grandpa
Export default {name: 'children', methods: {setMsg () {this.$emit (' eventOne', '123')} 11. Pass parameters
How to pass multiple parameters in resolve in promise
/ / similar to this, but in fact, the last two parameters cannot be obtained promise = new Promise ((resolve,reject) = > {let a = 1 let b = 2 let c = 3 resolve (ameme bjorc)}) promise.then ((ameme bjorc) = > {console.log (adre bjorc)}))
Resolve () can only accept and process one parameter, and the extra parameters will be ignored.
If you want to use more than one array, or object way.
Array
Promise = new Promise ((resolve,reject) = > {resolve ([1Jing 2jue 3])}) promise.then ((arr) = > {console.log (arr [0], arr [1], arr [2])})
Object
Promise = new Promise ((resolve,reject) = > {resolve ({aburet 1) bRV 2) promise.then (obj= > {console.log (obj.a,obj.b,obj.c)}) Twelve. Global variable
Define a global variable, assign it directly to the component with value, and use it directly within the component you need.
These are all the contents of this article entitled "what are the ways to transmit data in vuejs?" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.