What are the several ways to pass data in vuejs

青灯夜游
Release: 2023-01-11 09:22:08
Original
1863 people have browsed it

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.

What are the several ways to pass data in vuejs

The operating environment of this tutorial: windows7 system, vue2.9.6 version, DELL G3 computer.

1. Parent-to-child transfer

(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=&#39;name&#39;></son> 
  </p>
</template>

<script>
import son from "./son.vue";//导入父组件
export default {
  components: { son },//注册组件
  name: "父组件",
  data() {
    return {
      name: "Frazier", //父组件定义变量
    };
  },
};
</script>
Copy after login
//子组件
<template>
  <p>{{data}}</p>
</template>

<script>
export default {
components: { },
  name: &#39;子组件&#39;,
  props:["data"],
};
</script>
Copy after login

2. Pass from child to parent

(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(&#39;子传父&#39;)
    }
  },
};
</script>
Copy after login
//子组件
<template>
  <p>
    <button @click="lcalter">点我</button>
  </p>
</template>

<script>
export default {
components: { },
  name: &#39;子组件&#39;,
  methods: {
    lcalter(){
      this.$emit(&#39;lcclick&#39;)//通过emit来触发事件
    }
  },
};
</script>
Copy after login

3. Brother component communication (bus bus)

(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:

What are the several ways to pass data in vuejs

What are the several ways to pass data in vuejs

What are the several ways to pass data in vuejs

##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 &#39;./child.vue&#39;
  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>
Copy after login
//子组件
<template>
  <p>child 的内容</p>
</template>
<script>
export default {
  data () {
    return {
      name: &#39;我是 child&#39;,
    }
  },
  methods: {
    sayHello () {
      console.log(&#39;hello&#39;);
      alert(&#39;hello&#39;);
    }
  }
}
</script>
Copy after login

5. Vuex communication

The component passes dispatch to actions. Actions are asynchronous operations. In actions, you commit to mutations. Mutations then change the state through logical operations, thereby synchronizing to the component and updating its data state.

Code example:

//父组件
template>
  <p id="app">
    <ChildA/>
    <ChildB/>
  </p>
</template>
<script>
  import ChildA from &#39;./ChildA&#39; // 导入A组件
  import ChildB from &#39;./ChildB&#39; // 导入B组件
  export default {
    components: {ChildA, ChildB} // 注册组件
  }
</script>
Copy after login
//子组件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: &#39;Hello,B组件,我是A组件&#39;
     }
   },
   computed: {
     BMessage() {
       // 这里存储从store里获取的B组件的数据
       return this.$store.state.BMsg
     }
   },
   methods: {
     transform() {
       // 触发receiveAMsg,将A组件的数据存放到store里去
       this.$store.commit(&#39;receiveAMsg&#39;, {
         AMsg: this.AMessage
       })
     }
   }
 }
</script>
Copy after login
//子组件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: &#39;Hello,A组件,我是B组件&#39;
     }
   },
   computed: {
     AMessage() {
       // 这里存储从store里获取的A组件的数据
       return this.$store.state.AMsg
     }
   },
   methods: {
     transform() {
       // 触发receiveBMsg,将B组件的数据存放到store里去
       this.$store.commit(&#39;receiveBMsg&#39;, {
         BMsg: this.BMessage
       })
     }
   }
 }
</script>
Copy after login
//vuex
import Vue from &#39;vue&#39;
 import Vuex from &#39;vuex&#39;
 Vue.use(Vuex)
 const state = {
   AMsg: &#39;&#39;,
   BMsg: &#39;&#39;
 }
 
 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
 })
Copy after login

6.$parent

You can get the parent component instance through parent, and then you can access the properties and methods of the parent component through this instance. It also has a brother parent that can get the parent component instance, and then through this instance You can access the properties and methods of the parent component. It also has a brother parent that can get the parent component instance. Then you can access the properties and methods of the parent component through this instance. It also has a brother root that can get the root component instance.

Code example:

// 获父组件的数据
this.$parent.foo

// 写入父组件的数据
this.$parent.foo = 2

// 访问父组件的计算属性
this.$parent.bar

// 调用父组件的方法
this.$parent.baz()

//在子组件传给父组件例子中,可以使用this.$parent.getNum(100)传值给父组件。
Copy after login

7.sessionStorage passing value

sessionStorage is the global object of the browser, and the data stored in it will be closed on the page Clear when. Using this feature, we can share a copy of data across all pages.

Code example:

// 保存数据到 sessionStorage
sessionStorage.setItem(&#39;key&#39;, &#39;value&#39;);

// 从 sessionStorage 获取数据
let data = sessionStorage.getItem(&#39;key&#39;);

// 从 sessionStorage 删除保存的数据
sessionStorage.removeItem(&#39;key&#39;);

// 从 sessionStorage 删除所有保存的数据
sessionStorage.clear();
Copy after login

Note: It stores key-value pairs, which can only be string types. If you want to store objects, you need to use let objStr = JSON.stringify(obj) converts it into a string and then stores it (when using let obj = JSON.parse(objStr) parse it into an object).

Recommend a library good-storage, which encapsulates sessionStorage, and you can directly use its API to store objects

//localStorage
 storage.set(key,val) 
 storage.get(key, def)
//sessionStorage
 storage.session.set(key, val)
 storage.session.get(key, val)
Copy after login

8. Route value transfer

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 A

Please pay attention to router above The difference with route

Use colons to pass values

Configure the following route:

{
    path: &#39;/b/:name&#39;,
    name: &#39;b&#39;,
    component: () => import( &#39;../views/B.vue&#39;)
 },
Copy after login

On page B, you can pass this.$route.params.name To get the value of the name passed in by the route

Use the parent-child component to pass the value

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: [&#39;type&#39;]
watch: {
       type(){
           // console.log("在这个方法可以时刻获取最新的数据:type=",this.type)
       },
},
Copy after login

九.祖传孙 $attrs

正常情况下需要借助父亲的props作为中间过渡,但是这样在父亲组件就会多了一些跟父组件业务无关的属性,耦合度高,借助$attrs可以简化些,而且祖跟孙都无需做修改

祖组件:

<template>
    <section>
        <parent name="grandParent" sex="男" age="88" hobby="code" @sayKnow="sayKnow"></parent>
    </section>
</template>

<script>
    import Parent from &#39;./Parent&#39;
    export default {
        name: "GrandParent",
        components: {
          Parent
        },
        data() {
            return {}
        },
        methods: {
          sayKnow(val){
            console.log(val)
          }
        },
        mounted() {
        }
    }
</script>
Copy after login

父组件

<template>
  <section>
    <p>父组件收到</p>
    <p>祖父的名字:{{name}}</p>
    <children v-bind="$attrs" v-on="$listeners"></children>
  </section>
</template>

<script>
  import Children from &#39;./Children&#39;

  export default {
    name: "Parent",
    components: {
      Children
    },
    // 父组件接收了name,所以name值是不会传到子组件的
    props:[&#39;name&#39;],
    data() {
      return {}
    },
    methods: {},
    mounted() {
    }
  }
</script>
Copy after login

子组件

<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:[&#39;sex&#39;,&#39;age&#39;,&#39;hobby&#39;,&#39;name&#39;],
    data() {
      return {}
    },
    methods: {
      sayKnow(){
        this.$emit(&#39;sayKnow&#39;,&#39;我知道啦&#39;)
      }
    },
    mounted() {
    }
  }
</script>
Copy after login

十.孙传祖使用$listeners

文字内容同第九个

祖组件

<template>
  <p id="app">
    <children-one @eventOne="eventOne"></children-one>
    {{ msg }}
  </p>
</template>
<script>
import ChildrenOne from &#39;../src/components/children.vue&#39;
export default {
  name: &#39;App&#39;,
  components: {
    ChildrenOne,
  },
  data() {
    return {
      msg: &#39;&#39;
    }
  },
  methods: {
    eventOne(value) {
      this.msg = value
    }
  }
}
</script>
Copy after login

父组件

<template>
  <p>
    <children-two v-on="$listeners"></children-two>
  </p>
</template>

<script>
import ChildrenTwo from &#39;./childrenTwo.vue&#39;

export default {
  name: &#39;childrenOne&#39;,
  components: {
    ChildrenTwo
  }
}
</script>
Copy after login

子组件

<template>
  <p>
    <button @click="setMsg">点击传给祖父</button>
  </p>
</template>

<script>
export default {
  name: &#39;children&#39;,
  methods: {
    setMsg() {
      this.$emit(&#39;eventOne&#39;, &#39;123&#39;)
    }
  }
}
</script>
Copy after login

十一.promise传参

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)
})
Copy after login

resolve() 只能接受并处理一个参数,多余的参数会被忽略掉。

如果想多个用数组,或者对象方式。。

数组

promise = new Promise((resolve,reject)=>{
    resolve([1,2,3]) 
})
promise.then((arr)=>{
    console.log(arr[0],arr[1],arr[2])
})
Copy after login

对象

promise = new Promise((resolve,reject)=>{
    resolve({a:1,b:2,c:3}) 
})
promise.then(obj=>{
    console.log(obj.a,obj.b,obj.c)
})
Copy after login

十二.全局变量

定义一个全局变量,在有值的组件直接赋值,在需要的组件内直接使用就可以了,具体的话看我这篇博客就可以,
博客链接点击就好 全局变量 篇

到此这篇关于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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!