Transmission method: 1. Use "props" in the parent component to transfer data to the child component; 2. The child component uses "this.$emit("event")" to transfer data to the parent component; 3. Sibling components Use public files to transfer data between components; 4. Use "ref/refs" to transfer data between parent and child components; 5. Use Vuex to transfer data, etc.
The operating environment of this tutorial: windows7 system, vue2.9.6 version, DELL G3 computer.
(1) Bind an attribute on the child component label of the parent component and mount the variable to be transferred
(2) In Subcomponents receive data through props. Props can be arrays or objects. The received data can be directly used by props: ["property name"] props:{property name: data type}
Code example:
//父组件 <template> <p> <i>父组件</i> <!--页面使用--> <son :data='name'></son> </p> </template> <script> import son from "./son.vue";//导入父组件 export default { components: { son },//注册组件 name: "父组件", data() { return { name: "Frazier", //父组件定义变量 }; }, }; </script>
//子组件 <template> <p>{{data}}</p> </template> <script> export default { components: { }, name: '子组件', props:["data"], }; </script>
(1) Customize an event on the child component label of the parent component, and then call the required method
( 2) In the method of the child component, use this.$emit("event") to trigger the event defined in the parent component. The data is passed in the form of parameters.
Code example:
//父组件 <template> <p> <i>父组件</i> <!--页面使用--> <son @lcclick="lcclick"></son>//自定义一个事件 </p> </template> <script> import son from "./son.vue"; //导入父组件 export default { components: { son }, //注册组件 name: "父组件", data() { return {}; }, methods: { lcclick(){ alert('子传父') } }, }; </script>
//子组件 <template> <p> <button @click="lcalter">点我</button> </p> </template> <script> export default { components: { }, name: '子组件', methods: { lcalter(){ this.$emit('lcclick')//通过emit来触发事件 } }, }; </script>
(1) Create a new Bus.js file in src, and then export an empty vue instance
(2 ) Introduce Bus.js on the side that transmits data and then dispatch events through Bus. e m i t ("event name", "parameter"). The data is dispatched with emit("event name", "parameter"). The data Events are dispatched by emit("event name", "parameter"), and data are passed in the form of parameters of emit()
(3) Introduce Bus.js on the side that receives the data and then use Bus.$ on("Event name", (data)=>{data is the accepted data})
Picture example:
##IV.ref/refs (parent-child component communication) (1) ref if used on ordinary DOM elements , the reference points to the DOM element; if used on a subcomponent, the reference points to the component instance, (2) You can directly call the component's method or access data through the instance. It can also be regarded as a way for child components to pass values to parent components.
Code example:
//父组件 <template> <p> <button @click="sayHello">sayHello</button> <child ref="childForRef"></child> </p> </template> <script> 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() } } } </script>
//子组件 <template> <p>child 的内容</p> </template> <script> export default { data () { return { name: '我是 child', } }, methods: { sayHello () { console.log('hello'); alert('hello'); } } } </script>
Code example:
//父组件 template> <p id="app"> <ChildA/> <ChildB/> </p> </template> <script> import ChildA from './ChildA' // 导入A组件 import ChildB from './ChildB' // 导入B组件 export default { components: {ChildA, ChildB} // 注册组件 } </script>
//子组件A <template> <p id="childA"> <h1>我是A组件</h1> <button @click="transform">点我让B组件接收到数据</button> <p>因为点了B,所以信息发生了变化:{{BMessage}}</p> </p> </template> <script> export default { data() { return { AMessage: 'Hello,B组件,我是A组件' } }, computed: { BMessage() { // 这里存储从store里获取的B组件的数据 return this.$store.state.BMsg } }, methods: { transform() { // 触发receiveAMsg,将A组件的数据存放到store里去 this.$store.commit('receiveAMsg', { AMsg: this.AMessage }) } } } </script>
//子组件B <template> <p id="childB"> <h1>我是B组件</h1> <button @click="transform">点我让A组件接收到数据</button> <p>点了A,我的信息发生了变化:{{AMessage}}</p> </p> </template> <script> export default { data() { return { BMessage: 'Hello,A组件,我是B组件' } }, computed: { AMessage() { // 这里存储从store里获取的A组件的数据 return this.$store.state.AMsg } }, methods: { transform() { // 触发receiveBMsg,将B组件的数据存放到store里去 this.$store.commit('receiveBMsg', { BMsg: this.BMessage }) } } } </script>
//vuex import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const state = { AMsg: '', BMsg: '' } const mutations = { receiveAMsg(state, payload) { // 将A组件的数据存放于state state.AMsg = payload.AMsg }, receiveBMsg(state, payload) { // 将B组件的数据存放于state state.BMsg = payload.BMsg } } export default new Vuex.Store({ state, mutations })
Code example:
// 获父组件的数据 this.$parent.foo // 写入父组件的数据 this.$parent.foo = 2 // 访问父组件的计算属性 this.$parent.bar // 调用父组件的方法 this.$parent.baz() //在子组件传给父组件例子中,可以使用this.$parent.getNum(100)传值给父组件。
Code example:
// 保存数据到 sessionStorage sessionStorage.setItem('key', 'value'); // 从 sessionStorage 获取数据 let data = sessionStorage.getItem('key'); // 从 sessionStorage 删除保存的数据 sessionStorage.removeItem('key'); // 从 sessionStorage 删除所有保存的数据 sessionStorage.clear();
//localStorage storage.set(key,val) storage.get(key, def) //sessionStorage storage.session.set(key, val) storage.session.get(key, val)
Use question mark to pass Value
When page A jumps to page B, use this. ') Page B can use this.router.push('/B?name=danseek') Page B can use this.route.query.name to get the value passed from page APlease pay attention to router above The difference with routeUse colons to pass values
Configure the following route:{ path: '/b/:name', name: 'b', component: () => import( '../views/B.vue') },
Since the router-view itself is also a component, we can also use the parent-child component value pass method to pass the value, and then in the corresponding child Add props to the page. Because the route is not refreshed after the type is updated, you cannot directly obtain the latest type value in the mounted hook of the sub-page. Instead, you must use watch
<router-view :type="type"></router-view> // 子页面 props: ['type'] watch: { type(){ // console.log("在这个方法可以时刻获取最新的数据:type=",this.type) }, },
正常情况下需要借助父亲的props作为中间过渡,但是这样在父亲组件就会多了一些跟父组件业务无关的属性,耦合度高,借助$attrs可以简化些,而且祖跟孙都无需做修改
祖组件:
<template> <section> <parent name="grandParent" sex="男" age="88" hobby="code" @sayKnow="sayKnow"></parent> </section> </template> <script> import Parent from './Parent' export default { name: "GrandParent", components: { Parent }, data() { return {} }, methods: { sayKnow(val){ console.log(val) } }, mounted() { } } </script>
父组件
<template> <section> <p>父组件收到</p> <p>祖父的名字:{{name}}</p> <children v-bind="$attrs" v-on="$listeners"></children> </section> </template> <script> import Children from './Children' export default { name: "Parent", components: { Children }, // 父组件接收了name,所以name值是不会传到子组件的 props:['name'], data() { return {} }, methods: {}, mounted() { } } </script>
子组件
<template> <section> <p>子组件收到</p> <p>祖父的名字:{{name}}</p> <p>祖父的性别:{{sex}}</p> <p>祖父的年龄:{{age}}</p> <p>祖父的爱好:{{hobby}}</p> <button @click="sayKnow">我知道啦</button> </section> </template> <script> export default { name: "Children", components: {}, // 由于父组件已经接收了name属性,所以name不会传到子组件了 props:['sex','age','hobby','name'], data() { return {} }, methods: { sayKnow(){ this.$emit('sayKnow','我知道啦') } }, mounted() { } } </script>
文字内容同第九个
祖组件
<template> <p id="app"> <children-one @eventOne="eventOne"></children-one> {{ msg }} </p> </template> <script> import ChildrenOne from '../src/components/children.vue' export default { name: 'App', components: { ChildrenOne, }, data() { return { msg: '' } }, methods: { eventOne(value) { this.msg = value } } } </script>
父组件
<template> <p> <children-two v-on="$listeners"></children-two> </p> </template> <script> import ChildrenTwo from './childrenTwo.vue' export default { name: 'childrenOne', components: { ChildrenTwo } } </script>
子组件
<template> <p> <button @click="setMsg">点击传给祖父</button> </p> </template> <script> export default { name: 'children', methods: { setMsg() { this.$emit('eventOne', '123') } } } </script>
promise 中 resolve 如何传递多个参数
//类似与这样使用,但实际上后面两个参数无法获取 promise = new Promise((resolve,reject)=>{ let a = 1 let b = 2 let c = 3 resolve(a,b,c) }) promise.then((a,b,c)=>{ console.log(a,b,c) })
resolve() 只能接受并处理一个参数,多余的参数会被忽略掉。
如果想多个用数组,或者对象方式。。
数组
promise = new Promise((resolve,reject)=>{ resolve([1,2,3]) }) promise.then((arr)=>{ console.log(arr[0],arr[1],arr[2]) })
对象
promise = new Promise((resolve,reject)=>{ resolve({a:1,b:2,c:3}) }) promise.then(obj=>{ console.log(obj.a,obj.b,obj.c) })
定义一个全局变量,在有值的组件直接赋值,在需要的组件内直接使用就可以了,具体的话看我这篇博客就可以,
博客链接点击就好 全局变量 篇
到此这篇关于vue传值方式的十二种方法总结的文章就介绍到这了,更多相关vue传值方式内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关推荐:《vue.js教程》
The above is the detailed content of What are the several ways to pass data in vuejs. For more information, please follow other related articles on the PHP Chinese website!