vue 组件传值、页面(路由)传值

一、组件传值

1、父组件——>子组件(属性传值)

在父组件页面引入子组件并在,儿子身上绑定属性 :list = "list"

父组件页面data中填写要传递的值 list[a,b,c]

子组件页面接受

props: {
  list: {
    type: Array,
    default() {
    return [];
    }
  }
}
子组件页面就可以拿到值了 {{list[0]}}

2、子组件——》父组件(事件传值)

子组件中定义事件:

<div :class="['btn', show ? 'btn1' : '']" @click="showMenu"></div>;
通过$emit触发,第一个参数是事件名 第二个是要传递的数据;
showMenu() {
      this.show = !this.show;
      this.$emit('showMenu', this.show);
    },
在父组件页面引入子组件并在,儿子身上绑定 触发的事件名 @showMenu="toShowMenu";
通过参数接受传过来数据 
toShowMenu(v) {
     console.log(v)
   }
 
另外:this.$emit 也可以只传递一个事件名,不传递值。也就是只在子组件触发一个事件传过去。父组件通过该事件操作自己身上的值。。
子组件代码:
<van-button class="prev" type="default" @click="toPrev">上一项</van-button>

父组件代码:
<kcbl @toPrev="currentStep--;"/>

 3、父组件直接引用子组件身上的方法 ref。


子组件:

<template>
  <div>
    <!-- 把传递过来的参数进行页面渲染 -->
    <span>我是引用模板中的文字的小憨憨</span>
  </div>
</template>

<script>
export default {
  data() {
    return {
      hello: '我才有一个参数需要你进行接受'
    };
  }
};
</script>

父组件:

<template>
  <div class="content">
    <div class="text-area">
      <button @click="toGo">点击我哦</button>
    </div>
    <child-1 ref="hellosss"></child-1>
  </div>
</template>

<script>
import child1 from './child1';
export default {
  components: {
    child1
  },
  data() {
    return {
      title: 'Hello'
    };
  },
  methods: {
    toGo() {
      //拿到父组件的hello变量
      console.log('我是接受参数的', this.$refs.hellosss.hello);
      //输出:我是接受参数的 我才有一个参数需要你进行接受
    }
  },
  mounted() {
    //拿到父组件的hello变量
    console.log('我是接受参数的', this.$refs.hellosss.hello);
  },
};
</script>

 

 

参考: https://segmentfault.com/a/1190000011882494

posted @ 2020-07-17 17:53  伟笑  阅读(1728)  评论(0编辑  收藏  举报