vue组件传值的几种方式是什么-LMLPHP

本教程操作环境:windows7系统、vue2.9.6版,DELL G3电脑。

1、路由传参

步骤:

①定义路由时加上参数props: true,在定义路由路径时要留有参数占位符: name『用法:to="'路径/'+value"

②在跳转到的页面加上参数props:['name']

③在跳转到的页面就获取到了name『用法: js中直接this. name;html中直接插值{{ name}}

2、父组件向子组件传值

父组件向子组件传值就是通过在父组件中让子组件标签绑定父组件的数据,子组件的props接收父组件穿过来的值即可

步骤:

①父组件内设置要传的数据『data(){ parentid: value}

②在父组件中引用的子组件上绑定一个自定义属性并把数据绑定在自定义属性上『< myBtn :childid='parentid'></ mybtn>

③在子组件添加参数props:['childid'],即可

代码:

<div id="app">
	<mybtn :childid='parentid' title="我是标题"></mybtn>
</div>
<script>
	new Vue({
		el:"app",
		data:{
			parentid:"88888"
		},
		components:{
			"mybtn" : {
				props: ['childid','title'],
	  			template: '<button>我是{{childid}}号按钮{{title}}</button>'
			}
		}
	})
</script>
登录后复制

结果展示:

vue组件传值的几种方式是什么-LMLPHP

3、子组件向父组件传值

子传父的实现方式就是用了 this.e m i t 来遍历 getData 事件,首先用按钮来触发setData事件,在setData中用this.emit 来遍历 getData 事件,最后返回 this.msg

步骤:

①由于父组件需要参数,所以在父组件中的标签上定义自定义事件,在事件内部获取参数;『@myEvent=" callback"在callback函数中接收参数』

②在子组件中触发自定义事件,并传参。『this.$emit('父组件中的自定义事件',参数)

代码:

<template>
  <div>
	  <mybtn :style="{color:acolor,background:bcolor}" @changeColorEvent="getColor" :parentid="childid" title="我是标题"></mybtn>
  </div>

</template>
<script>

  export default {
    name : 'test',
    data () {
      return {
        childid:"666",
        acolor:'blue',
        bcolor:'red'
      }
    },
    methods:{
      getColor(colors){
        //父组件就可以拿到子组件传过来的colors
        console.log(colors)
        this.acolor = "white";
        this.bcolor = colors;
      },
      //接收多个参数
      /*getColor(colors1,colors2){
        console.log(colors1,colors2)
        this.acolor = colors2;
        this.bcolor = colors1;
      }*/
    },
    components: {
      'mybtn' : {
        props : ['parentid','title'],
        template : `
          <div class="box">
            <p>我最初是一张白纸</p>
            <button @click="changeColor">我是{{parentid}}号按钮{{title}}</button>
          </div>
        `,
        methods: {
          changeColor(){
          //这个方法是触发父组件中的事件,第一个参数是触发的事件名称。第二个参数及以后是向changeColorEvent传的参数
           this.$emit('changeColorEvent',"orange")
           //发送多个参数可以直接跟在后面
           //this.$emit('changeColorEvent',"orange","white")
          }
        }
      }
    }
  }
</script>
<style scoped>

</style>
登录后复制

vue组件传值的几种方式是什么-LMLPHP

4、非父组件之间传值

步骤:

(1)方法一、

①建立一个公共的通信组件(Vue),需要传值的组件里引入该通信组件

②在一个中绑定一个事件this.on('eventname', this. id)

③在另一个组件中触发事件this.$ emit('eventname',( options)=>{})

(2)方法二、

在本地存储中添加公共数据,可以在两个页面中获取,更改

【相关推荐:《vue.js教程》】

以上就是vue组件传值的几种方式是什么的详细内容,更多请关注Work网其它相关文章!

09-18 05:48